"""
ТО: три ошибки из разбора 23.09.2026 (TO_PROCESS, раздел 11, пункты 1, 3, 4).
"""

import pathlib

ROOT = pathlib.Path(__file__).resolve().parents[2]
APP = ROOT / "engine" / "timesheet"
DB = (APP / "supplydb.py").read_text(encoding="utf-8")
WEB = (APP / "webapp.py").read_text(encoding="utf-8")
SQL = (ROOT / "sql" / "75_maintenance_guard.sql").read_text(encoding="utf-8")


def block(src, head):
    at = src.index(head)
    return src[at:src.index("\ndef ", at + 10)]


# --- 1. ТО только у складской техники ---------------------------------------

def test_only_warehouse_equipment_gets_maintenance():
    body = block(DB, "def maintenance_due(")
    assert "AND c.is_equipment" in body
    assert "coalesce(c.group_code, '') <> %s" in body


def test_marking_checks_the_kind_of_item():
    body = block(DB, "def _check_maintainable(")
    assert 'not row["is_equipment"]' in body
    assert "VERIFICATION_GROUP" in body
    assert "written_off" in body


# --- 3. Своё депо -------------------------------------------------------------

def test_the_machine_must_belong_to_the_depot_of_the_form():
    body = block(DB, "def _check_maintainable(")
    assert 'row["org_unit_id"] != unit_id' in body
    assert WEB.count('unit_id=u["id"]') >= 2
    assert "_check_maintainable(conn, asset_id, unit_id)" in block(
        DB, "def mark_maintenance_done(")
    assert "_check_maintainable(conn, asset_id, unit_id)" in block(
        DB, "def save_meter(")


def test_the_database_guards_maintenance_by_depot():
    for table in ("maintenance", "meter_reading"):
        assert f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY" in SQL
    assert SQL.count("has_perm('maintenance.do')") == 4
    assert "CREATE TRIGGER maintenance_audit" in SQL


# --- 4. Моточасы ---------------------------------------------------------------

def test_hours_cannot_be_negative():
    body = block(DB, "def mark_maintenance_done(")
    assert "float(done_hours) < 0" in body
    assert "maintenance_hours_nonneg" in SQL
    assert "meter_reading_hours_nonneg" in SQL


def test_hours_do_not_run_backwards_even_backdated():
    body = block(DB, "def _check_hours_order(")
    assert "done_at <= %(d)s" in body and "done_at > %(d)s" in body
    assert "Счётчик моточасов назад не идёт" in body
    assert "_check_hours_order(conn, asset_id, done_at, float(done_hours))" in \
        block(DB, "def mark_maintenance_done(")
