"""
02.10.2026 — правки по вычитке LOGIKA_PROSTO и сквозному прогону процессов
по кабинетам (Claude). Тест держит то, что заказчик решил, чтобы следующая
правка не вернула прежнее поведение молча.
"""

import datetime as dt
import pathlib

ROOT = pathlib.Path(__file__).resolve().parents[2]
ENGINE = ROOT / "engine" / "timesheet"


def read(p: pathlib.Path) -> str:
    return p.read_text(encoding="utf-8")


WEB = read(ENGINE / "webapp.py")
WEBDB = read(ENGINE / "webdb.py")
SQL = {p.name: read(p) for p in (ROOT / "sql").glob("1[01][0-9]_*.sql")}


# ------------------------------------------------------------ кабинеты служб

def test_service_cabinets_are_read_only():
    from timesheet.webdb import is_read_only, start_page
    assert is_read_only({"roles": ["oz"]})
    assert is_read_only({"roles": ["ot", "management"]})
    assert not is_read_only({"roles": ["oz", "rc_head"]})
    assert start_page({"roles": ["oz"]}) == "/purchase"
    assert start_page({"roles": ["ot"]}) == "/safety"
    assert start_page({"roles": ["management"]}) == "/board"
    assert start_page({"roles": ["viewer"]}) == "/staff"
    assert start_page({"roles": ["rc_head"]}) == "/kanban?span=day"


def test_oz_role_gets_its_cabinet_and_head_loses_minsk_steps():
    sql = SQL["106_rights_and_locks.sql"]
    assert "WHERE r.code = 'oz'" in sql and "p.code = 'supply.oz'" in sql
    assert "(r.code = 'rc_head' AND p.code = 'repair.hq')" in sql


def test_timesheet_and_schedule_are_locked_in_the_database():
    sql = SQL["106_rights_and_locks.sql"]
    assert "NOT has_perm('timesheet.write')" in sql
    assert "has_perm('timesheet.approve')" in sql
    assert "CREATE TRIGGER schedule_plan_guard" in sql
    assert "has_perm('schedule.reopen')" in sql


def test_cancel_hire_clears_the_candidate_link():
    assert "employment_id = NULL" in SQL["106_rights_and_locks.sql"]


# ------------------------------------------------------------ ремонт

def test_repair_steps_belong_to_their_side():
    from timesheet.supplydb import step_allowed
    #  депо: отправить и принять
    assert step_allowed("minsk", "new", "sent_to_hq", can_hq=False, can_open=True)
    assert step_allowed("minsk", "sent_to_unit", "received",
                        can_hq=False, can_open=True)
    assert not step_allowed("minsk", "sent_to_hq", "hq_received",
                            can_hq=False, can_open=True)
    #  Минск: свои шаги, но не приёмка за склад
    assert step_allowed("minsk", "sent_to_hq", "hq_received",
                        can_hq=True, can_open=True)
    assert not step_allowed("minsk", "sent_to_unit", "received",
                            can_hq=True, can_open=True)
    #  отменить после отправки — только Минск
    assert not step_allowed("minsk", "sent_to_hq", "cancelled",
                            can_hq=False, can_open=True)


def test_repair_outcome_is_chosen_on_close():
    sql = SQL["107_repair_roles_and_outcome.sql"]
    assert "outcome IN ('ok', 'not_fixed', 'needs_replacement')" in sql
    assert "asset_status_before" in sql


# ------------------------------------------------------------ сотрудники

def test_rehire_starts_documents_anew():
    sql = SQL["110_rehire_and_briefings.sql"]
    assert "CREATE OR REPLACE FUNCTION app.employee_current_since" in sql
    assert "m.passed_at >= v_since" in sql
    assert "held_at >= v_since" in sql


def test_fuel_card_is_filled_by_the_administration():
    at = WEB.index("def staff_fuel(")
    body = WEB[at:WEB.index("\n@app.", at)]
    assert 'has_perm(conn, "hiring.confirm")' in body


def test_over_headcount_needs_the_tick_on_confirmation_too():
    at = WEB.index("def staff_confirm(")
    body = WEB[at:WEB.index("\n@app.", at)]
    assert 'hc["over"] and confirm_headcount != "yes"' in body


# ------------------------------------------------------------ расписание

def test_last_day_shift_must_end_at_midnight():
    assert "В последний день месяца смена — до 24:00" in WEB


def test_mid_month_person_has_a_reduced_norm_in_the_timesheet():
    from timesheet.webapp import person_month_norm
    #  без календаря (пустой) норма возвращается полной — занижать молча нельзя
    assert person_month_norm(None, 176.0, dt.date(2026, 10, 1), None, None) == 176.0


def test_board_asks_for_last_month_timesheet_and_next_month_schedule():
    k = read(ENGINE / "kanbandb.py")
    assert "ts_task(prev, month.replace(day=5))" in k
    assert "if today.day >= 20:" in k and "sched_task(nxt, last_day)" in k
    assert "    if day.day == 1:\n" in k


def test_payroll_follows_the_timesheet():
    sql = SQL["113_payroll_follows_timesheet.sql"]
    assert "CREATE TRIGGER timesheet_day_marks_payroll" in sql
    assert "CREATE TRIGGER payroll_stale_guard" in sql


def test_two_kinds_of_work_order_on_one_date():
    from timesheet.compare import compare
    from timesheet.totals import FactDay
    day = dt.date(2026, 9, 26)
    both = [FactDay(work_date=day, hours_day=11.0, hours_weekend=8.0,
                    hours_overtime=3.0)]
    assert compare([], both, ordered={day: "overtime+weekend"}) == []


def test_social_leave_fits_in_one_record():
    from timesheet.vacationdb import MAX_DAYS
    assert MAX_DAYS["social"] >= 160 and MAX_DAYS["labour"] == 60


# ------------------------------------------------------------ обеспечение

def test_inventory_number_carries_the_depot_code():
    sql = SQL["115_inventory_prefix.sql"]
    assert "('brest', 1), ('vitebsk', 2)" in sql


def test_maintenance_rules_come_from_the_reference():
    from timesheet.kanbandb import maintenance_is_due
    today = dt.date(2026, 10, 2)
    #  новый вид «вызов специалиста» объявляется по правилу 25-го
    assert maintenance_is_due("ТО-9", dt.date(2026, 10, 20), None, today,
                              announce="month25")
    #  новый вид «своими силами» — день в день
    assert maintenance_is_due("ТО-8", today, None, today, announce="day")
    assert not maintenance_is_due("ТО-8", dt.date(2026, 10, 3), None, today,
                                  announce="day")


def test_supply_counters_are_the_filter():
    s = read(ENGINE / "templates" / "supply.html")
    assert '<nav class="cards tight filter-cards"' in s
    assert 'tab: str = "equipment", status: str = "ok",' in WEB


def test_ppe_act_names_go_first():
    from timesheet.ppe_act_print import person_line
    assert person_line({"full_name": "Шечин Евгений Валерьевич",
                        "position": "Начальник"}) == "Шечин Е.В., Начальник"
