"""
Заявка на ремонт: два маршрута и акт (23.09.2026).

«Разбить заявку на 2 группы. В ремонт: 1. Вызов специалиста в Депо,
 2. Отправить в Минск». Уточнения: акт не обязателен, но его можно
приложить — фото или PDF; специалиста вызывают и депо, и Минск; открытые
заявки старого маршрута вернуть в исходное состояние — «Исправно».
"""

import pathlib
import sys

ROOT = pathlib.Path(__file__).resolve().parents[2]
APP = ROOT / "engine" / "timesheet"
SQL = (ROOT / "sql" / "71_repair_routes.sql").read_text(encoding="utf-8")
DB = (APP / "supplydb.py").read_text(encoding="utf-8")
WEB = (APP / "webapp.py").read_text(encoding="utf-8")
PART = (APP / "templates" / "_repair.html").read_text(encoding="utf-8")
SUPPLY = (APP / "templates" / "supply.html").read_text(encoding="utf-8")
CARD = (APP / "templates" / "asset_card.html").read_text(encoding="utf-8")
BACKUP = (ROOT / "tools" / "make_backup.py").read_text(encoding="utf-8")

sys.path.insert(0, str(ROOT / "engine"))
from timesheet import filestore, supplydb                    # noqa: E402


# --- два маршрута ------------------------------------------------------------

def test_the_two_routes_are_named_as_the_customer_named_them():
    assert supplydb.REPAIR_ROUTE_RU == {
        "specialist": "Вызов специалиста в депо",
        "minsk": "Отправить в Минск",
    }


def test_the_specialist_route_has_three_steps():
    assert supplydb.REPAIR_FLOWS["specialist"] == [
        ("new", "Заявка открыта"),
        ("specialist_called", "Вызов специалиста"),
        ("fixed", "Произведён ремонт"),
    ]


def test_the_minsk_route_keeps_its_seven_steps_with_the_customers_words():
    labels = [label for _, label in supplydb.REPAIR_FLOWS["minsk"]]
    assert labels == [
        "Заявка открыта", "Передано в Минск", "Минск подтвердил получение",
        "Отправлено в ремонт", "Вернулась с ремонта", "Отправлено в депо",
        "Приняло депо",
    ]


def test_the_route_is_stored_with_the_request():
    assert "ADD COLUMN IF NOT EXISTS route text NOT NULL DEFAULT 'minsk'" in SQL
    assert "CHECK (route IN ('specialist', 'minsk'))" in SQL


def test_a_step_of_one_route_cannot_land_in_the_other():
    """«Передано в Минск» у заявки на вызов специалиста — ошибка, а не вариант."""
    assert "repair_request_route_status" in SQL
    assert ("OR (route = 'specialist' AND status IN "
            "('specialist_called', 'fixed'))") in SQL


def test_the_next_steps_depend_on_the_route():
    assert "FUNCTION repair_next_statuses(p_route text, p_status text)" in SQL
    assert "SELECT app.repair_next_statuses(%s, %s) AS s" in DB


def test_a_route_is_chosen_on_opening_and_is_mandatory():
    assert 'if route not in REPAIR_ROUTE_RU:' in DB
    assert 'route: str = Form(""),' in WEB
    #  Заранее не отмечен ни один: выбор должен быть осознанным
    assert 'type="radio" name="route"' in PART
    assert "checked" not in PART.split("macro route_pick")[1].split("endmacro")[0]


def test_every_opening_form_asks_for_the_route():
    """Заявку открывают из трёх мест, и во всех трёх спрашивают маршрут."""
    assert SUPPLY.count("rp.route_pick()") == 2
    assert CARD.count("rp.route_pick()") == 1


def test_repairing_on_site_makes_the_unit_working_again():
    at = SQL.index("CREATE OR REPLACE FUNCTION move_repair_request")
    body = SQL[at:SQL.index("$fn$;", at)]
    assert "IF p_status IN ('received', 'fixed') THEN" in body


def test_the_closed_states_are_written_once():
    assert supplydb.REPAIR_CLOSED == ("received", "fixed", "cancelled")
    assert "NOT IN ('received', 'cancelled')" not in DB
    kanban = (APP / "kanbandb.py").read_text(encoding="utf-8")
    assert "NOT IN ('received', 'cancelled')" not in kanban


# --- кто двигает -------------------------------------------------------------

def test_the_specialist_is_called_by_the_depot_too():
    """«В обоих случаях могут вызывать»: мастер встречает специалиста на месте."""
    at = SQL.index("CREATE OR REPLACE FUNCTION move_repair_request")
    body = SQL[at:SQL.index("$fn$;", at)]
    assert "IF v_req.route = 'specialist' THEN" in body
    assert "has_perm('repair.open')" in body


def test_the_minsk_steps_stay_with_the_administration():
    at = SQL.index("CREATE OR REPLACE FUNCTION move_repair_request")
    body = SQL[at:SQL.index("$fn$;", at)]
    assert ("IF p_status IN ('hq_received', 'in_repair', 'repaired', "
            "'sent_to_unit')") in body
    assert "AND NOT has_perm('repair.hq') THEN" in body


def test_the_screen_follows_the_same_rule():
    #  02.10.2026: кнопки шагов отбирает supplydb.step_allowed — то же
    #  правило, что держит база
    assert "supplydb.step_allowed(" in WEB
    assert "r.route == 'specialist'" in SUPPLY


# --- старые заявки -----------------------------------------------------------

def test_open_requests_of_the_old_route_are_closed_and_units_are_working():
    """«Вернуть их в первоначальную стадию (ИСПРАВНО)»."""
    at = SQL.index("--  4. Открытые заявки старого маршрута")
    block = SQL[at:]
    assert "SET status = 'cancelled', closed_at = now()" in block
    assert "UPDATE asset a SET status = 'ok'" in block
    assert "a.status = 'repair'" in block


def test_they_are_cancelled_not_deleted():
    """История прежних шагов остаётся в карточке техники."""
    at = SQL.index("--  4. Открытые заявки старого маршрута")
    block = SQL[at:]
    assert "DELETE" not in block
    assert "Закрыта при переходе на два маршрута ремонта" in block


# --- акты --------------------------------------------------------------------

def test_an_act_is_optional():
    """Закрытие заявки акта не спрашивает."""
    at = SQL.index("CREATE OR REPLACE FUNCTION move_repair_request")
    body = SQL[at:SQL.index("$fn$;", at)]
    assert "repair_act" not in body


def test_an_act_carries_its_date():
    assert "act_date     date   NOT NULL" in SQL
    assert 'name="act_date" required' in PART


def test_the_file_is_kept_on_disk_not_in_the_database():
    """Акты копятся годами — в базе только сведения о файле."""
    at = SQL.index("CREATE TABLE IF NOT EXISTS repair_act")
    table = SQL[at:SQL.index(");", at)]
    assert "bytea" not in table
    assert "stored_name" in table and "sha256" in table


def test_the_file_type_is_decided_by_its_content():
    assert filestore.sniff(b"\xff\xd8\xff\xe0rest") == "image/jpeg"
    assert filestore.sniff(b"\x89PNG\r\n\x1a\nrest") == "image/png"
    assert filestore.sniff(b"RIFF\x00\x00\x00\x00WEBPrest") == "image/webp"
    assert filestore.sniff(b"%PDF-1.7 rest") == "application/pdf"
    #  Переименованный исполняемый файл фотографией не становится
    assert filestore.sniff(b"MZ\x90\x00rest") is None


def test_a_file_is_written_whole_or_not_at_all(tmp_path, monkeypatch):
    monkeypatch.setenv("FILES_DIR", str(tmp_path))
    got = filestore.save(b"%PDF-1.4 test", "repair")
    path = filestore.path_of(got.stored_name)
    assert path.read_bytes() == b"%PDF-1.4 test"
    assert got.mime_type == "application/pdf"
    assert len(got.sha256) == 64
    assert not list(tmp_path.rglob("*.part"))


def test_empty_big_and_foreign_files_are_refused(tmp_path, monkeypatch):
    import pytest
    monkeypatch.setenv("FILES_DIR", str(tmp_path))
    for data in (b"", b"MZ" + b"0" * 10,
                 b"%PDF-" + b"0" * filestore.MAX_BYTES):
        with pytest.raises(filestore.FileRejected):
            filestore.save(data, "repair")
    assert not list(tmp_path.rglob("*.*"))


def test_a_path_cannot_leave_the_store(tmp_path, monkeypatch):
    import pytest
    monkeypatch.setenv("FILES_DIR", str(tmp_path))
    with pytest.raises(filestore.FileRejected):
        filestore.path_of("../../windows/system32/config")


def test_the_store_lives_outside_the_application_folder(monkeypatch):
    """Обновление меняет код и папку хранилища трогать не должно."""
    monkeypatch.delenv("FILES_DIR", raising=False)
    monkeypatch.setenv("LOCALAPPDATA", "C:/Users/x/AppData/Local")
    assert filestore.root().as_posix().endswith("ooucr/files")


def test_a_file_that_the_database_refused_is_removed():
    at = DB.index("def add_repair_act(")
    body = DB[at:DB.index("\ndef ", at + 10)]
    assert "filestore.remove(stored.stored_name)" in body


def test_the_act_is_given_out_only_to_its_depot():
    """Два рубежа: RLS на таблице и проверка депо при выдаче файла."""
    assert "CREATE POLICY repair_act_unit ON repair_act" in SQL
    at = WEB.index("def supply_repair_act_file(")
    body = WEB[at:WEB.index("\n@app.", at)]
    assert 'webdb.can_access_unit(conn, act["org_unit_id"])' in body
    assert 'content_disposition_type="inline"' in body


def test_only_the_administration_deletes_an_act():
    """02.10.2026 (вычитка 5.20): начальник акты не удаляет."""
    at = WEB.index("def supply_repair_act_drop(")
    body = WEB[at:WEB.index("\n@app.", at)]
    assert 'if not webdb.has_perm(conn, "repair.hq"):' in body


def test_acts_are_shown_in_the_requests_and_in_the_card():
    assert "rp.acts_block(r, acts, unit.code)" in SUPPLY
    assert "rp.acts_block(r, acts, unit.code, 'card', asset.id)" in CARD


def test_the_backup_takes_the_acts_too():
    """Иначе база восстановится со ссылками в пустоту."""
    assert "def zip_files(" in BACKUP
    assert 'tabel_faily_{stamp}.zip' in BACKUP
