"""
Доработки от 23.09.2026 («Доработка.docx» и замечания по доске задач).
"""

import pathlib
import sys
from datetime import date

ROOT = pathlib.Path(__file__).resolve().parents[2]
APP = ROOT / "engine" / "timesheet"
WEB = (APP / "webapp.py").read_text(encoding="utf-8")
WEBDB = (APP / "webdb.py").read_text(encoding="utf-8")
KANBAN = (APP / "kanbandb.py").read_text(encoding="utf-8")
T = APP / "templates"
SQL73 = (ROOT / "sql" / "73_settlement_by_hq.sql").read_text(encoding="utf-8")

sys.path.insert(0, str(ROOT / "engine"))
from timesheet.cells import (fact_cell_parts, merge_fact_part,  # noqa: E402
                             parse_fact_cell)
from timesheet import webapp, webdb                              # noqa: E402


def read(name):
    return (T / name).read_text(encoding="utf-8")


# --- отпуска у начальника ---------------------------------------------------

def test_the_vacation_form_follows_the_vacation_right():
    """Форма показывалась по праву кадров, а обработчики спрашивали другое."""
    assert '"can_vacation": webdb.has_perm(conn, "vacation.write")' in WEB
    assert "{% if can_vacation %}" in read("vacations.html")


# --- причины увольнения в справочниках --------------------------------------

def test_termination_reasons_live_among_the_references():
    s = read("settings.html")
    at = s.index("Причины увольнения и непродления контракта")
    positions = s.index("{% elif tab == 'positions' %}")
    codes = s.index("{% elif tab == 'codes' %}")
    assert positions < at < codes
    assert '_settings_back("positions", msg="Признак изменён")' in WEB


# --- табель: буква не пропадает ---------------------------------------------

def test_the_letter_stays_in_the_cell():
    assert fact_cell_parts(parse_fact_cell("РВ 11"))["day"] == "РВ 11"
    assert fact_cell_parts(parse_fact_cell("4 С"))["day"] == "4 С"
    assert fact_cell_parts(parse_fact_cell("10 С 3"))["day"] == "10 С3"
    assert fact_cell_parts(parse_fact_cell("8"))["day"] == "8"


def test_the_letter_in_front_is_accepted_for_overtime_too():
    c = parse_fact_cell("С 4")
    assert c.hours_day == 4 and c.hours_overtime == 4


def test_what_the_cell_shows_is_accepted_back_unchanged():
    """Открыл клетку, ничего не поменял, ушёл — ни ошибки, ни потери признака."""
    for raw, night in (("РВ 11", None), ("Я 8 С 2", None), ("Я 8 РВ 3", None),
                       ("РВ 7", "РВ 4"), ("7 С", "С 4"), ("8", "С 3")):
        c = merge_fact_part(None, "day", raw)
        if night:
            c = merge_fact_part(c, "night", night)
        shown = fact_cell_parts(c)["day"]
        assert merge_fact_part(c, "day", shown) == c, (raw, night, shown)


# --- вызовы и сверхурочные за год --------------------------------------------

def test_the_year_limits_are_twelve_calls_and_180_hours():
    assert webdb.CALLS_YEAR_LIMIT == 12
    assert webdb.OVERTIME_YEAR_LIMIT == 180
    assert webdb.limits_text({"calls": 1, "overtime": 6.0}) == {
        "calls_year": "1/12", "overtime_year": "6/180"}


def test_a_call_is_a_day_and_overtime_is_hours_counted_per_person():
    at = WEBDB.index("def year_limits(")
    body = WEBDB[at:WEBDB.index("\ndef ", at + 5)]
    assert "count(DISTINCT td.work_date)" in body
    assert "FILTER (WHERE td.hours_weekend > 0)" in body
    assert "sum(td.hours_overtime)" in body
    #  по человеку: перевод счёт не обнуляет
    assert "em.employee_id = em0.employee_id" in body
    assert "date(until.year, 1, 1)" in body


def test_the_columns_keep_their_names_and_show_the_limits():
    g = read("grid.html")
    assert ">Вызовы</th>" in g and ">Сверхур.</th>" in g
    assert 'data-t="calls_year"' in g and 'data-t="overtime_year"' in g
    assert "lim-over" in g and "lim-near" in g


# --- доска: сегодня, неделя, месяц -------------------------------------------

def test_each_span_has_its_own_label_and_arrows():
    nav = webapp._kanban_span_nav
    today = date(2026, 9, 23)
    d = nav("day", today, date(2026, 9, 21), today)
    assert d["period_label"] == "23.09.2026, среда" and d["is_current"]
    assert d["next_q"] == "span=day&day=2026-09-24"
    w = nav("week", date(2026, 9, 21), date(2026, 9, 21), today)
    assert w["period_label"] == "21.09 — 27.09.2026"
    m = nav("month", date(2026, 9, 1), date(2026, 9, 21), today)
    assert m["period_label"] == "сентябрь 2026" and m["is_current"]
    assert m["prev_q"] == "span=month&month=2026-08"


def test_the_span_buttons_lead_to_the_current_period():
    k = read("kanban.html")
    assert 'href="/kanban?unit={{ unit.code }}&view={{ view }}&span={{ code }}{{ flt_q }}"' in k


def test_marking_a_task_returns_to_the_same_period():
    assert 'name="nav" value="{{ nav }}"' in read("kanban.html")
    assert webapp._kanban_back("2026-09-21", "span=day&day=2026-09-24") \
        == "span=day&day=2026-09-24"
    #  в хвост адреса нельзя подсунуть что угодно
    assert webapp._kanban_back("2026-09-21", "x=1&y=<script>") == "week=2026-09-21"


def test_a_ppe_task_links_to_the_person_even_after_the_issue_is_gone():
    at = KANBAN.index("def subject_urls(")
    body = KANBAN[at:KANBAN.index("\ndef board", at)]
    assert "if key in issues and key not in people" in body
    assert "if len(ids) == 1:" in body


# --- окончательный расчёт ----------------------------------------------------

def test_the_depot_sends_without_calculating():
    at = SQL73.index("CREATE OR REPLACE FUNCTION submit_settlement")
    body = SQL73[at:SQL73.index("$fn$;", at)]
    assert "payroll_run" not in body


def test_the_administration_cannot_accept_what_nobody_calculated():
    at = SQL73.index("CREATE OR REPLACE FUNCTION accept_settlement")
    body = SQL73[at:SQL73.index("$fn$;", at)]
    assert "r.kind = 'final'" in body
    assert "Окончательный расчёт ещё не посчитан" in body


def test_only_the_administration_calculates():
    assert '"can_calc": webdb.has_perm(conn, "payroll.calc") and is_hq' in WEB
    assert "Окончательный расчёт считает Администрация" in WEB


def test_the_administration_downloads_one_employees_timesheet():
    assert "employment: int | None = None" in WEB
    assert 'rows_db = [r for r in rows_db if r["employment_id"] == employment]' in WEB
    assert "Скачать табель сотрудника" in read("settlement.html")


def test_the_staff_tabs_stay_on_the_settlement_page():
    assert '{% include "_staff_nav.html" %}' in read("settlement.html")
    assert '{% include "_staff_nav.html" %}' in read("staff.html")
    assert 'class="subtabs big"' in read("_staff_nav.html")
