"""
Загрузка табеля из печатной формы.

Табель — подписанный документ, и разбор его клеток не имеет права
расходиться с тем, что считал человек. Поэтому здесь проверяются два вида
правил: как читается клетка из двух половин формы и как определяется месяц.

Половины: слева часы дневные или обозначение дня, справа — ночные. Код дня
и ночные часы в одной клетке — не ошибка: работа с 22:00 до 08:00 даёт хвост
на следующие сутки, а сами эти сутки человек может быть уже в отпуске. В
табеле депо за август 2026 такая клетка есть.
"""

import pathlib
import sys
from datetime import date, datetime

import pytest

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "tools"))

import import_fact as imp  # noqa: E402


# ---------------------------------------------------------------------------
#  Табельный номер
# ---------------------------------------------------------------------------

def test_personnel_number_from_a_number_in_the_form():
    assert imp.personnel_no(3014910990) == "3014910990"
    assert imp.personnel_no("3014910990") == "3014910990"
    assert imp.personnel_no(" 3014910990 ") == "3014910990"


def test_personnel_number_survives_excel_float():
    assert imp.personnel_no(3014910990.0) == "3014910990"


def test_garbage_instead_of_a_number_is_refused():
    assert imp.personnel_no(None) is None
    assert imp.personnel_no("итого") is None
    assert imp.personnel_no("") is None


# ---------------------------------------------------------------------------
#  Клетка из двух половин
# ---------------------------------------------------------------------------

def test_day_hours_only():
    cell = imp.merge_halves("11", "")
    assert (cell.hours_day, cell.hours_night) == (11.0, 0.0)
    assert cell.day_code is None


def test_day_and_night_halves():
    #  Смена 4 часа днём и 7 ночью — так стоит в форме за 4 августа
    cell = imp.merge_halves("4", "7")
    assert (cell.hours_day, cell.hours_night) == (4.0, 7.0)


def test_day_code_alone():
    assert imp.merge_halves("В", "").day_code == "В"
    assert imp.merge_halves("О", "").day_code == "О"


def test_military_training_code_is_understood():
    #  «ГЧ» — военно-учебные сборы: в табеле депо он есть, и раньше загрузка
    #  на нём останавливалась
    assert imp.merge_halves("ГЧ", "").day_code == "ГЧ"


def test_code_with_night_hours_keeps_both():
    #  «О» слева и «2» справа: человек в отпуске, но два ночных часа с
    #  прошлой смены отработаны. Терять их нельзя
    cell = imp.merge_halves("О", "2")
    assert cell.day_code == "О"
    assert cell.hours_night == 2.0
    assert cell.hours_day == 0.0


def test_empty_cell_is_empty():
    assert imp.merge_halves("", "").is_empty


def test_weekend_and_overtime_marks_survive():
    assert imp.merge_halves("РВ 4", "").hours_weekend == 4.0
    assert imp.merge_halves("4 С 8", "8").hours_overtime == 8.0


def test_unparsable_cell_raises():
    from timesheet.cells import CellError
    with pytest.raises(CellError):
        imp.merge_halves("вчера", "")


# ---------------------------------------------------------------------------
#  Месяц табеля
# ---------------------------------------------------------------------------

class FakeSheet:
    """Лист из одной клетки «за <месяц>» — заменяет openpyxl."""

    def __init__(self, value):
        self.value = value

    def __getitem__(self, coord):
        assert coord == imp.PERIOD_CELL
        return type("C", (), {"value": self.value})


def test_period_comes_from_the_form():
    assert imp.period_of(FakeSheet(datetime(2026, 8, 1))) == date(2026, 8, 1)
    assert imp.period_of(FakeSheet(date(2026, 8, 15))) == date(2026, 8, 1)


def test_period_can_be_given_explicitly():
    assert imp.period_of(FakeSheet(None), "2026-08") == date(2026, 8, 1)


def test_month_without_a_date_is_refused_loudly():
    #  Гадать по имени файла нельзя: ошибка уйдёт в чужой месяц
    with pytest.raises(SystemExit, match="--period"):
        imp.period_of(FakeSheet("август"))


def test_garbage_period_is_refused():
    with pytest.raises(SystemExit, match="2026-08"):
        imp.period_of(FakeSheet(None), "август")


# ---------------------------------------------------------------------------
#  Геометрия формы — та же, что у выгрузки
# ---------------------------------------------------------------------------

def test_geometry_matches_the_export():
    from timesheet import tabel_print as tp
    assert imp.FIRST_DAY_COL == tp.FIRST_DAY_COL
    assert imp.FIRST_DATA_ROW == tp.FIRST_DATA_ROW
    assert imp.SUMMARY_COL == tp.SUMMARY_COL
    assert imp.DAY_SLOTS == tp.DAY_SLOTS


def test_summary_columns_point_at_hours_and_night():
    #  BU — «Раб. часы», BV — «Раб. часы ночь»: по ним идёт сверка
    from timesheet import tabel_print as tp
    titles = [short for _long, short, _key in tp.SUMMARY_HEADERS]
    assert titles[imp.SUM_HOURS - imp.SUMMARY_COL] == "Раб. часы"
    assert titles[imp.SUM_NIGHT - imp.SUMMARY_COL] == "Раб. часы ночь"


def test_days_in_month_is_counted_not_guessed():
    assert imp._days_in_month(date(2026, 8, 1)) == 31
    assert imp._days_in_month(date(2026, 2, 1)) == 28
    assert imp._days_in_month(date(2026, 12, 1)) == 31


# ---------------------------------------------------------------------------
#  Поиск файла: табель узнаётся по форме, а не по имени
# ---------------------------------------------------------------------------
#
#  Рядом с проектом лежат «Расчет ЗП Депо Барановичи» и «Управление РЦ
#  Барановичи»: по слову в названии табель от них не отличить. Загрузка на
#  чужом файле падала на «в клетке B11 нет даты месяца», и понять из этого,
#  что взялся не тот файл, было нельзя.

def _write_book(path: pathlib.Path, head: dict[int, str] | None = None):
    import openpyxl
    wb = openpyxl.Workbook()
    ws = wb.active
    for col, text in (head or {}).items():
        ws.cell(imp.HEAD_ROW, col).value = text
    wb.save(path)
    return path


def _tabel_head() -> dict[int, str]:
    return {imp.COL_FIO: "Фамилия И.О.",
            imp.COL_PERSONNEL: "Таб. №",
            imp.COL_POSITION: "Должность"}


def test_the_form_is_recognised_by_its_header(tmp_path):
    assert imp.looks_like_tabel(_write_book(tmp_path / "т.xlsx", _tabel_head()))


def test_another_workbook_of_the_depot_is_not_a_tabel(tmp_path):
    #  Имя со словом «Барановичи», а внутри не табель
    path = _write_book(tmp_path / "Расчет ЗП Депо Барановичи v2.6.xlsx",
                       {1: "Расчет заработной платы"})
    assert not imp.looks_like_tabel(path)


def test_a_broken_file_is_not_a_tabel(tmp_path):
    #  Поиск перебирает все таблицы подряд, и битая не должна его ронять
    path = tmp_path / "мусор.xlsx"
    path.write_bytes(b"not a workbook")
    assert not imp.looks_like_tabel(path)


def test_search_skips_lookalikes_and_returns_the_real_form(tmp_path, monkeypatch):
    monkeypatch.setattr(pathlib.Path, "home", staticmethod(lambda: tmp_path / "нет"))
    _write_book(tmp_path / "Управление РЦ Барановичи v.2.5.2.xlsx", {1: "Депо"})
    real = _write_book(tmp_path / "Барановичи 08-26.xlsx", _tabel_head())

    path, seen = imp.find_file(tmp_path)
    assert path == real
    #  Похожее по имени пробуется первым, поэтому отвергнутого может и не быть;
    #  главное — что вернулся именно табель
    assert "Барановичи 08-26.xlsx" not in seen


def test_search_reports_what_it_looked_at(tmp_path, monkeypatch):
    monkeypatch.setattr(pathlib.Path, "home", staticmethod(lambda: tmp_path / "нет"))
    _write_book(tmp_path / "Расчет ЗП.xlsx", {1: "Расчет"})
    _write_book(tmp_path / "Управление РЦ.xlsx", {1: "Депо"})

    path, seen = imp.find_file(tmp_path)
    assert path is None
    #  Без этого списка человек не поймёт, почему «файл не найден», когда
    #  таблицы рядом лежат
    assert sorted(seen) == ["Расчет ЗП.xlsx", "Управление РЦ.xlsx"]


def test_search_looks_into_downloads(tmp_path, monkeypatch):
    #  Табель приходит письмом и лежит в «Загрузках», а не в папке приложения
    home = tmp_path / "home"
    (home / "Downloads").mkdir(parents=True)
    monkeypatch.setattr(pathlib.Path, "home", staticmethod(lambda: home))
    real = _write_book(home / "Downloads" / "Барановичи 08-26.xlsx", _tabel_head())

    project = tmp_path / "проект"
    project.mkdir()
    path, _seen = imp.find_file(project)
    assert path == real


def test_temporary_excel_files_are_ignored(tmp_path, monkeypatch):
    #  «~$…» — файл открытой в Excel книги, читать его нельзя
    monkeypatch.setattr(pathlib.Path, "home", staticmethod(lambda: tmp_path / "нет"))
    (tmp_path / "~$Барановичи 08-26.xlsx").write_bytes(b"lock")
    path, seen = imp.find_file(tmp_path)
    assert path is None and seen == []


def test_an_explicitly_given_file_is_checked_too(tmp_path, capsys):
    #  Раньше --file принимался на веру, и ошибка уходила в разбор клеток
    wrong = _write_book(tmp_path / "Расчет ЗП.xlsx", {1: "Расчет"})
    assert imp.main(["--file", str(wrong), "--dsn", "postgresql:///nowhere"]) == 2
    assert "не похож на табель" in capsys.readouterr().err
