"""Тесты разбора клеток табеля и графика."""

from datetime import time

import pytest

from timesheet.cells import (
    CellError,
    FactCell,
    PlanCell,
    build_fact_cell,
    format_fact_cell,
    format_plan_cell,
    parse_fact_cell,
    parse_plan_cell,
)


# ---------------------------------------------------------------------------
#  Табель
# ---------------------------------------------------------------------------

def test_plain_hours():
    c = parse_fact_cell("11")
    assert (c.hours_day, c.hours_night, c.day_code) == (11.0, 0.0, None)


def test_hours_with_comma():
    assert parse_fact_cell("7,5").hours_day == 7.5


def test_day_night_pair():
    c = parse_fact_cell("4/7")
    assert (c.hours_day, c.hours_night) == (4.0, 7.0)
    assert c.worked == 11.0


@pytest.mark.parametrize("raw, code", [
    ("В", "В"), ("в", "В"), ("О", "О"), ("оЖ", "ОЖ"), ("ож", "ОЖ"), ("П", "П"),
])
def test_day_codes(raw, code):
    assert parse_fact_cell(raw).day_code == code


def test_weekend_work():
    c = parse_fact_cell("РВ 4")
    assert (c.hours_day, c.hours_weekend) == (4.0, 4.0)


def test_weekend_work_without_space():
    """Именно этот ввод сейчас теряется молча: РВ4 без пробела."""
    c = parse_fact_cell("РВ4")
    assert (c.hours_day, c.hours_weekend) == (4.0, 4.0)


def test_overtime():
    c = parse_fact_cell("4 С")
    assert (c.hours_day, c.hours_overtime) == (4.0, 4.0)


def test_overtime_without_space():
    c = parse_fact_cell("4С")
    assert c.hours_overtime == 4.0


def test_stacker_suffix_no_longer_accepted():
    """Часы на штабелере из проекта убраны: суффикс Ш должен внятно отказать,
    а не молча пропасть вместе с числом."""
    for raw in ("11 Ш6", "4/7 Ш3", "Ш6"):
        with pytest.raises(CellError):
            parse_fact_cell(raw)


def test_empty_cell():
    assert parse_fact_cell("").is_empty
    assert parse_fact_cell(None).is_empty
    assert parse_fact_cell("   ").is_empty


def test_more_than_24_hours_rejected():
    with pytest.raises(CellError, match="24 часов"):
        parse_fact_cell("25")


def test_pair_over_24_rejected():
    with pytest.raises(CellError, match="24 часов"):
        parse_fact_cell("14/12")


def test_zero_hours_rejected():
    with pytest.raises(CellError, match="больше нуля"):
        parse_fact_cell("0")


def test_garbage_rejected_with_hint():
    with pytest.raises(CellError, match="Ожидается число часов"):
        parse_fact_cell("вчера был")


# ---------------------------------------------------------------------------
#  Обратный вывод
# ---------------------------------------------------------------------------

@pytest.mark.parametrize("raw, shown", [
    ("11", "11"),
    ("7,5", "7,5"),
    ("4/7", "4/7"),
    ("В", "В"),
    ("РВ 4", "РВ 4"),
    ("РВ4", "РВ 4"),
    ("4 С", "4 С"),
    ("", ""),
])
def test_roundtrip(raw, shown):
    """Что напечатали — то и увидели после сохранения."""
    assert format_fact_cell(parse_fact_cell(raw)) == shown


# ---------------------------------------------------------------------------
#  График
# ---------------------------------------------------------------------------

def test_shift_full_format():
    c = parse_plan_cell("09:00-21:00")
    assert (c.shift_start, c.shift_end) == (time(9), time(21))


def test_shift_short_format():
    c = parse_plan_cell("9-21")
    assert (c.shift_start, c.shift_end) == (time(9), time(21))


def test_shift_with_spaces_and_dash_variants():
    for raw in ("9 - 21", "09:00 – 21:00", "9—21"):
        c = parse_plan_cell(raw)
        assert (c.shift_start, c.shift_end) == (time(9), time(21))


def test_night_shift_across_midnight():
    c = parse_plan_cell("20:00-08:00")
    assert (c.shift_start, c.shift_end) == (time(20), time(8))


def test_plan_day_code():
    assert parse_plan_cell("В").day_code == "В"


def test_plan_same_start_and_end_rejected():
    with pytest.raises(CellError, match="совпадают"):
        parse_plan_cell("09:00-09:00")


def test_plan_bad_time_rejected():
    with pytest.raises(CellError):
        parse_plan_cell("25:00-30:00")


def test_plan_garbage_rejected_with_hint():
    with pytest.raises(CellError, match="09:00-21:00"):
        parse_plan_cell("утром")


@pytest.mark.parametrize("raw, shown", [
    ("09:00-21:00", "09:00-21:00"),
    ("9-21", "09:00-21:00"),
    ("20:00-08:00", "20:00-08:00"),
    ("В", "В"),
    ("", ""),
])
def test_plan_roundtrip(raw, shown):
    assert format_plan_cell(parse_plan_cell(raw)) == shown


# ---------------------------------------------------------------------------
#  Экран смены: сборка клетки из отдельных полей
# ---------------------------------------------------------------------------

def test_build_empty_row_is_empty_cell():
    cell = build_fact_cell()
    assert cell.is_empty
    assert format_fact_cell(cell) == ""


def test_build_blank_strings_are_zero():
    cell = build_fact_cell(hours_day="", hours_night=None, hours_weekend="")
    assert cell.is_empty


def test_build_day_and_night():
    cell = build_fact_cell(hours_day="4", hours_night="7")
    assert (cell.hours_day, cell.hours_night, cell.worked) == (4.0, 7.0, 11.0)
    assert format_fact_cell(cell) == "4/7"


def test_build_accepts_comma_decimal():
    assert build_fact_cell(hours_day="7,5").hours_day == 7.5


def test_build_day_code_alone():
    cell = build_fact_cell(day_code="о")
    assert cell.day_code == "О" and cell.worked == 0


def test_build_unknown_day_code_rejected():
    with pytest.raises(CellError, match="Неизвестный код дня"):
        build_fact_cell(day_code="Ы")


def test_build_code_with_hours_rejected():
    with pytest.raises(CellError, match="закрыт кодом"):
        build_fact_cell(day_code="В", hours_day="8")


def test_build_hours_without_worked_time_rejected():
    with pytest.raises(CellError, match="без отработанного"):
        build_fact_cell(hours_weekend="3")


def test_build_over_24_rejected():
    with pytest.raises(CellError, match="24 часов"):
        build_fact_cell(hours_day="13", hours_night="12")


def test_build_negative_rejected():
    with pytest.raises(CellError, match="отрицательным"):
        build_fact_cell(hours_day="-4")


def test_build_not_a_number_rejected():
    with pytest.raises(CellError, match="не число"):
        build_fact_cell(hours_day="восемь")


def test_build_weekend_over_worked_rejected():
    with pytest.raises(CellError, match="работы в выходной"):
        build_fact_cell(hours_day="8", hours_weekend="9")


def test_build_partial_overtime_kept():
    """Часть смены сверхурочные — так в текстовой записи выразить было нельзя."""
    cell = build_fact_cell(hours_day="11", hours_overtime="3")
    assert cell.worked == 11.0 and cell.hours_overtime == 3.0


def test_build_weekend_and_overtime_over_worked_rejected():
    with pytest.raises(CellError, match="вместе"):
        build_fact_cell(hours_day="8", hours_weekend="5", hours_overtime="5")


def test_build_full_weekend_shift_reads_back_as_text():
    cell = build_fact_cell(hours_day="4", hours_weekend="4")
    assert format_fact_cell(cell) == "РВ 4"


# ---------------------------------------------------------------------------
#  Расширенный справочник обозначений
# ---------------------------------------------------------------------------

@pytest.mark.parametrize("raw, code", [
    ("ОБ", "ОБ"), ("об", "ОБ"),
    ("ОД", "ОД"), ("ДО", "ДО"),
    ("У", "У"), ("Т", "Т"), ("Г", "Г"),
    ("ПВ", "ПВ"), ("ПР", "ПР"), ("НН", "НН"),
])
def test_new_day_codes_parsed(raw, code):
    assert parse_fact_cell(raw).day_code == code


def test_single_letter_code_not_eaten_by_two_letter(raw=None):
    """«О» и «ОБ» — разные коды, сравнение точное по всей клетке."""
    assert parse_fact_cell("О").day_code == "О"
    assert parse_fact_cell("ОБ").day_code == "ОБ"


def test_work_letters_are_not_day_codes():
    """Я, Н, С, РВ — это часы, а не код дня: в клетку кодом не ставятся."""
    for raw in ("Я", "Н"):
        with pytest.raises(CellError):
            parse_fact_cell(raw)


def test_rv_alone_is_not_a_code_but_rv_with_hours_works():
    with pytest.raises(CellError):
        parse_fact_cell("РВ")
    assert parse_fact_cell("РВ 4").hours_weekend == 4.0


def test_every_entry_code_has_a_colour():
    from timesheet.cells import CODE_KIND, DAY_CODES
    missing = [c for c in DAY_CODES if c not in CODE_KIND]
    assert not missing, f"без цвета остались коды: {missing}"


def test_plan_cell_lines_two_lines():
    from timesheet.cells import plan_cell_lines
    assert plan_cell_lines(parse_plan_cell("9-18")) == ["09:00 -", "18:00"]
    assert plan_cell_lines(parse_plan_cell("20:00-08:00")) == ["20:00 -", "08:00"]
    assert plan_cell_lines(parse_plan_cell("В")) == ["В"]
    assert plan_cell_lines(parse_plan_cell("")) == []


# ---------------------------------------------------------------------------
#  Табель половинами: дневная и ночная колонки на одну дату
# ---------------------------------------------------------------------------

from timesheet.cells import fact_cell_parts, merge_fact_part  # noqa: E402


def test_night_part_keeps_day_part():
    day = merge_fact_part(None, "day", "11")
    both = merge_fact_part(day, "night", "4")
    assert (both.hours_day, both.hours_night, both.worked) == (11.0, 4.0, 15.0)


def test_day_part_keeps_night_part():
    night = merge_fact_part(None, "night", "7")
    both = merge_fact_part(night, "day", "4")
    assert (both.hours_day, both.hours_night) == (4.0, 7.0)


def test_clearing_day_part_keeps_night():
    both = merge_fact_part(merge_fact_part(None, "day", "4"), "night", "7")
    only_night = merge_fact_part(both, "day", "")
    assert (only_night.hours_day, only_night.hours_night) == (0.0, 7.0)


def test_clearing_both_parts_empties_the_cell():
    both = merge_fact_part(merge_fact_part(None, "day", "4"), "night", "7")
    step = merge_fact_part(both, "day", "")
    assert merge_fact_part(step, "night", "").is_empty


def test_day_code_closes_whole_day_and_drops_night():
    both = merge_fact_part(merge_fact_part(None, "day", "4"), "night", "7")
    coded = merge_fact_part(both, "day", "О")
    assert coded.day_code == "О"
    assert coded.hours_day == 0 and coded.hours_night == 0


def test_night_hours_rejected_when_day_is_coded():
    coded = merge_fact_part(None, "day", "Б")
    with pytest.raises(CellError, match="закрыт кодом"):
        merge_fact_part(coded, "night", "4")


def test_weekend_marker_survives_night_edit():
    rv = merge_fact_part(None, "day", "РВ 4")
    assert rv.hours_weekend == 4.0
    with_night = merge_fact_part(rv, "night", "3")
    assert with_night.hours_weekend == 4.0 and with_night.hours_night == 3.0


def test_subset_markers_clamped_when_hours_shrink():
    """Было 11 часов, все сверхурочные; стало 4 — сверхурочных не может быть 11."""
    big = merge_fact_part(None, "day", "11 С")
    assert big.hours_overtime == 11.0
    small = merge_fact_part(big, "day", "4")
    assert small.hours_overtime == 4.0
    assert small.hours_overtime <= small.worked


def test_over_24_across_both_parts_rejected():
    day = merge_fact_part(None, "day", "20")
    with pytest.raises(CellError, match="24 часов"):
        merge_fact_part(day, "night", "6")


def test_night_part_takes_numbers_only():
    with pytest.raises(CellError, match="не число"):
        merge_fact_part(None, "night", "О")


def test_parts_for_display():
    both = merge_fact_part(merge_fact_part(None, "day", "4"), "night", "7")
    p = fact_cell_parts(both)
    assert p["day"] == "4" and p["night"] == "7"
    assert "ночные 7 ч" in p["title"]

    coded = merge_fact_part(None, "day", "В")
    assert fact_cell_parts(coded) == {"day": "В", "night": "", "title": "В"}
    assert fact_cell_parts(None) == {"day": "", "night": "", "title": ""}

    rv = merge_fact_part(None, "day", "РВ 4")
    #  23.09.2026: буква видна в клетке — «обозначение не должно пропадать»
    assert fact_cell_parts(rv)["day"] == "РВ 4"
    assert "работа в выходной 4 ч" in fact_cell_parts(rv)["title"]


def test_fallback_reference_covers_every_entry_code():
    """
    Запасной справочник должен знать все коды, которые можно вводить.

    «ОБ» — исключение: разбор клетки его ещё понимает, чтобы дни в базе без
    накатанной миграции 31 читались, а не падали, но в справочник он уже не
    входит и в ввод не предлагается.
    """
    from timesheet.cells import DAY_CODES, day_code_reference_fallback
    ref = {r["code"] for r in day_code_reference_fallback()}
    missing = [c for c in DAY_CODES if c not in ref and c != "ОБ"]
    assert not missing, f"нет в запасном справочнике: {missing}"


def test_the_retired_code_is_still_understood():
    #  В базе, где миграцию 31 не накатили, дни с «ОБ» должны читаться
    from timesheet.cells import DAY_CODES, parse_fact_cell
    assert "ОБ" in DAY_CODES
    assert parse_fact_cell("ОБ").day_code == "ОБ"


def test_fallback_reference_marks_work_letters_as_not_enterable():
    from timesheet.cells import day_code_reference_fallback
    by_code = {r["code"]: r for r in day_code_reference_fallback()}
    #  «Я», «Н», «С», «РВ» — обозначения работы: они выводятся часами, а не
    #  вводятся буквой
    for code in ("Я", "Н", "С", "РВ"):
        assert by_code[code]["entry"] is False, code
    #  «А» — отпуск без сохранения заработной платы (решение от 14.09.2026).
    #  Прежде это обозначалось «ОБ», и «А» числилось устаревшим; теперь
    #  наоборот, «ОБ» убрано из справочника миграцией 31
    for code in ("В", "О", "Б", "К", "А", "ПР"):
        assert by_code[code]["entry"] is True, code
    assert "ОБ" not in by_code


def test_fallback_reference_kinds_match_cell_colouring():
    """Цвет в справочнике и цвет клетки не должны расходиться."""
    from timesheet.cells import CODE_KIND, day_code_reference_fallback
    for r in day_code_reference_fallback():
        if r["entry"]:
            assert r["kind"] == CODE_KIND[r["code"]], r["code"]
