"""Photographer app (/shoot): counts declared on the phone, a fence per class, no clocks involved."""
import os
import time
import uuid
from pathlib import Path

import pytest
from PIL import Image

from core import config
from services import organizer_service as O
from services import photographer_service, school_service, shoot_service
from services.shoot_service import (KIND_CHILD, KIND_CLASS, KIND_END, KIND_SKIP, KIND_UNDO, build_runs,
                                     claimed_names, open_run, sort_capture_order)

PH = photographer_service.IMPLICIT_PHOTOGRAPHER


def _dir(sid, code):
    """The folder the organizer gave a child (`{Clase}/Student N`, see photo_service): a storage key."""
    from services import photo_service
    dirs = photo_service.family_dirs(sid, code)
    assert len(dirs) == 1, dirs
    return dirs[0][1]


def _names(sid, code) -> list:
    """Names of the files stored in a child's folder."""
    from core import storage
    return sorted(f.name for f in storage.files(_dir(sid, code)))


def ev(i, kind, target=None, **meta):
    return {"id": i, "at": 0.0, "kind": kind, "target": target, "meta": meta}


# ── Runs (pure) ────────────────────────────────────────────────────────────────────────────────

def test_a_run_collects_children_skips_and_its_fence():
    runs = build_runs([
        ev(1, KIND_CLASS, "3A", before=["stray.jpg"]),
        ev(2, KIND_CHILD, "2"), ev(3, KIND_SKIP, "1"), ev(4, KIND_CHILD, "3"),
        ev(5, KIND_END, files=["a", "b", "c", "d", "e", "f"]),
    ])
    assert len(runs) == 1
    r = runs[0]
    assert r.class_name == "3A" and r.closed and r.before == ["stray.jpg"]
    assert r.items == [("child", 2), ("skip", 1), ("child", 3)]
    assert r.declared == 6 and r.children == 2 and r.files == ["a", "b", "c", "d", "e", "f"]


def test_undo_removes_only_the_last_item_and_only_in_the_open_run():
    runs = build_runs([ev(1, KIND_CLASS, "3A"), ev(2, KIND_CHILD, "2"), ev(3, KIND_CHILD, "3"), ev(4, KIND_UNDO)])
    assert runs[0].items == [("child", 2)]
    assert open_run([ev(1, KIND_CLASS, "3A")]).class_name == "3A"


def test_a_new_class_closes_the_previous_one_and_events_outside_a_run_are_ignored():
    runs = build_runs([
        ev(1, KIND_CHILD, "2"),                       # no class open: ignored
        ev(2, KIND_CLASS, "3A"), ev(3, KIND_CHILD, "1"),
        ev(4, KIND_CLASS, "4B"), ev(5, KIND_CHILD, "2"),
    ])
    assert [(r.class_name, r.closed, r.declared) for r in runs] == [("3A", True, 1), ("4B", False, 2)]
    assert runs[0].files is None                       # closed without a fence: it can never be assigned


def test_events_are_folded_in_insertion_order_not_by_time():
    late_clock = {"id": 1, "at": 9e9, "kind": KIND_CLASS, "target": "3A", "meta": {}}
    early_clock = {"id": 2, "at": 1.0, "kind": KIND_CHILD, "target": "2", "meta": {}}
    assert build_runs([early_clock, late_clock])[0].declared == 2


def test_only_closed_unprocessed_runs_claim_files():
    runs = build_runs([
        ev(1, KIND_CLASS, "3A"), ev(2, KIND_END, files=["a", "b"]),
        ev(3, KIND_CLASS, "4B"), ev(4, KIND_END, files=["c"]),
        ev(5, KIND_CLASS, "5C"),
    ])
    assert claimed_names(runs, processed=0) == {"a", "b", "c"}
    assert claimed_names(runs, processed=2) == {"c"}


def test_capture_order_is_natural_so_dsc_9_comes_before_dsc_10(tmp_path):
    paths = [tmp_path / n for n in ("DSC_0010.JPG", "DSC_0009.JPG", "DSC_0002.JPG")]
    assert [p.name for p in sort_capture_order(paths, lambda p: None)] == ["DSC_0002.JPG", "DSC_0009.JPG", "DSC_0010.JPG"]


def test_class_qr_roundtrip_and_rejects_foreign_text():
    payload = shoot_service.class_qr_payload("ecole-x", "CE1 B")
    assert shoot_service.parse_class_qr(payload) == ("ecole-x", "CE1 B")
    for bad in ("https://photos.meeconic.com/?code=ABC-123-XYZ", "MEEC:CLASS:../etc:3A", "", None):
        assert shoot_service.parse_class_qr(bad) is None


# ── Helpers for the folder ───────────────────────────────────────────────────────────────────────────

def _jpeg(path: Path, color=(120, 90, 200), age: float = 0.0):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", (160, 120), color).save(path, "JPEG")
    if age:
        t = time.time() - age
        os.utime(path, (t, t))


def _drop(folder: Path, *names, age: float = 0.0):
    for i, n in enumerate(names):
        _jpeg(folder / n, color=(10 * i % 255, 90, 200), age=age)


# ── API (the phone) ───────────────────────────────────────────────────────────────────────────

@pytest.fixture
async def phone(client, admin_token):
    """A fresh school with two classes, the shooting mode on and a phone link."""
    h = {"Authorization": f"Bearer {admin_token}"}
    name = f"Shoot {uuid.uuid4().hex[:5]}"
    sid = (await client.post("/api/admin/schools", json={"name": name}, headers=h)).json()["school"]["id"]
    admin = {**h, "X-School": sid}
    for c in ("3A", "4B"):
        await client.post("/api/admin/classes", json={"name": c}, headers=admin)
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": True}}, headers=admin)
    await client.post("/api/admin/shoot/token", headers=admin)
    link = (await client.get("/api/admin/shoot", headers=admin)).json()
    token = link["link"].split("t=")[1]
    folder = O.incoming_dir_for(sid)
    folder.mkdir(parents=True, exist_ok=True)
    return {"sid": sid, "admin": admin, "tok": {"X-Shoot-Token": token}, "classes": link["classes"], "folder": folder}


def _qr(phone, name):
    return next(c["qr"] for c in phone["classes"] if c["class_name"] == name)


async def _post(client, phone, path, **body):
    return await client.post(f"/api/shoot/{path}", json={"photographer": PH, **body}, headers=phone["tok"])


async def test_phone_needs_a_valid_link(client, phone):
    assert (await client.get("/api/shoot/info")).status_code == 401
    assert (await client.get("/api/shoot/info", headers={"X-Shoot-Token": "x" * 30})).status_code == 401
    info = (await client.get("/api/shoot/info", headers=phone["tok"])).json()
    assert info["school_id"] == phone["sid"] and info["classes"] == ["3A", "4B"]
    assert info["enabled"] is True and info["max_per_child"] == 3


async def test_rotating_the_link_revokes_the_old_one(client, phone):
    await client.post("/api/admin/shoot/token", headers=phone["admin"])
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).status_code == 401


async def test_class_qr_of_another_school_or_unknown_class_is_refused(client, phone):
    foreign = shoot_service.class_qr_payload("otra-escuela", "3A")
    assert (await _post(client, phone, "class", qr=foreign)).status_code == 400
    unknown = shoot_service.class_qr_payload(phone["sid"], "9Z")
    assert (await _post(client, phone, "class", qr=unknown)).status_code == 400
    assert (await _post(client, phone, "class", qr="https://example.test")).status_code == 400
    bad = await client.post("/api/shoot/class", json={"photographer": "nadie", "class_name": "3A"}, headers=phone["tok"])
    assert bad.status_code == 400


async def test_children_need_an_open_class_and_respect_the_limit(client, phone):
    assert (await _post(client, phone, "child", count=2)).status_code == 409        # nothing scanned yet
    assert (await _post(client, phone, "class", qr=_qr(phone, "3A"))).status_code == 200
    assert (await _post(client, phone, "child", count=3)).status_code == 200
    # four photos in one tap is how two children end up on one code: refused
    assert (await _post(client, phone, "child", count=4)).status_code == 400
    assert (await _post(client, phone, "undo")).status_code == 200
    assert (await _post(client, phone, "undo")).status_code == 409                    # nothing left to undo


async def test_live_counts_compare_what_was_declared_with_what_arrived(client, phone):
    await _post(client, phone, "class", qr=_qr(phone, "3A"))
    await _post(client, phone, "child", count=2)
    live = (await client.get("/api/shoot/status", headers=phone["tok"])).json()["live"][PH]
    assert live["declared"] == 2 and live["received"] == 0 and live["ok"] is False
    _drop(phone["folder"], "DSC_0001.JPG", "DSC_0002.JPG")
    live = (await client.get("/api/shoot/status", headers=phone["tok"])).json()["live"][PH]
    assert live["received"] == 2 and live["ok"] is True and live["children"] == 1


async def test_files_taken_before_the_class_are_strays_and_never_count(client, phone):
    _drop(phone["folder"], "DSC_0001.JPG")                                            # shot with no class open
    r = await _post(client, phone, "class", qr=_qr(phone, "3A"))
    assert r.json()["strays"] == 1
    await _post(client, phone, "child", count=1)
    _drop(phone["folder"], "DSC_0002.JPG")
    live = (await client.get("/api/shoot/status", headers=phone["tok"])).json()["live"][PH]
    assert live["received"] == 1 and live["declared"] == 1 and live["ok"] is True


def _jpeg_bytes(size=(200, 120)) -> bytes:
    import io
    buf = io.BytesIO()
    Image.new("RGB", size, (200, 80, 80)).save(buf, "JPEG")
    return buf.getvalue()


async def test_test_camera_is_refused_unless_the_school_enabled_it(client, phone):
    r = await client.post(f"/api/shoot/photo?photographer={PH}", content=_jpeg_bytes(), headers=phone["tok"])
    assert r.status_code == 403
    assert not list(phone["folder"].glob("*.jpg"))
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).json()["test_camera"] is False


async def test_test_camera_photo_arrives_like_an_ftp_file_and_counts(client, phone):
    await client.put("/api/admin/settings", json={"settings": {"shoot_test_camera": True}}, headers=phone["admin"])
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).json()["test_camera"] is True
    await _post(client, phone, "class", qr=_qr(phone, "3A"))
    await _post(client, phone, "child", count=2)
    for _ in range(2):
        r = await client.post(f"/api/shoot/photo?photographer={PH}", content=_jpeg_bytes(), headers=phone["tok"])
        assert r.status_code == 200, r.text
    files = sorted(f.name for f in phone["folder"].iterdir())
    assert len(files) == 2 and all(n.endswith(".jpg") and not n.startswith(".") for n in files)
    assert files == sorted(files)                                   # stamp sorts in shooting order
    live = r.json()["live"]
    assert live["declared"] == 2 and live["received"] == 2 and live["ok"] is True


async def test_test_camera_rejects_non_images_and_unknown_photographers(client, phone):
    await client.put("/api/admin/settings", json={"settings": {"shoot_test_camera": True}}, headers=phone["admin"])
    r = await client.post(f"/api/shoot/photo?photographer={PH}", content=b"not an image", headers=phone["tok"])
    assert r.status_code == 400
    r = await client.post("/api/shoot/photo?photographer=ghost", content=_jpeg_bytes(), headers=phone["tok"])
    assert r.status_code == 400
    r = await client.post(f"/api/shoot/photo?photographer={PH}", content=_jpeg_bytes())
    assert r.status_code == 401
    assert not list(phone["folder"].iterdir())


async def test_ending_a_class_takes_the_fence_and_a_new_class_starts_clean(client, phone):
    await _post(client, phone, "class", qr=_qr(phone, "3A"))
    await _post(client, phone, "child", count=2)
    _drop(phone["folder"], "DSC_0001.JPG", "DSC_0002.JPG")
    closed = (await _post(client, phone, "end")).json()["closed"]
    assert closed == {"class_name": "3A", "declared": 2, "received": 2, "children": 1, "ok": True}

    # photos of the next class arrive before the previous one is processed: they are not the old class's
    await _post(client, phone, "class", qr=_qr(phone, "4B"))
    await _post(client, phone, "child", count=1)
    _drop(phone["folder"], "DSC_0003.JPG")
    live = (await client.get("/api/shoot/status", headers=phone["tok"])).json()["live"][PH]
    assert live["received"] == 1 and live["ok"] is True
    runs = build_runs(shoot_service.events_for(phone["sid"], PH))
    assert runs[0].files == ["DSC_0001.JPG", "DSC_0002.JPG"] and runs[1].before == []


# ── Organizer, end to end ────────────────────────────────────────────────────────────────────────

@pytest.fixture
def shoot_org(tmp_path, monkeypatch):
    sid = f"shoot-{uuid.uuid4().hex[:6]}"
    school_service.create_school("Shoot Org", slug=sid)
    from core.db import get_db
    with get_db() as conn:
        conn.execute("INSERT INTO school_classes (school_id, name) VALUES (?,?)", (sid, "3A"))
        conn.execute("INSERT INTO school_classes (school_id, name) VALUES (?,?)", (sid, "4B"))
        conn.commit()
    school_service.update_settings(sid, {"shoot_mode": True})
    monkeypatch.setattr(config, "FTP_STABLE_SECS", 0.0)
    monkeypatch.setattr(config, "PURGE_MIN_AGE_SECS", 0.0)
    alerts = []
    monkeypatch.setattr("services.alert_service.notify", lambda key, subject, body="": alerts.append(key))
    O._status_by_school.pop(sid, None)
    # the fence is read from the school's real incoming folder, so the organizer must watch that very folder
    incoming = O.incoming_dir_for(sid)
    incoming.mkdir(parents=True, exist_ok=True)
    org = O.PhotoOrganizer(sid, incoming)
    org.alerts = alerts
    return sid, org


def _run(sid, class_name, items, files, ph=PH):
    """Record a closed class exactly as the phone API does."""
    shoot_service.record_event(sid, ph, KIND_CLASS, class_name, {"before": []})
    for kind, n in items:
        shoot_service.record_event(sid, ph, kind, str(n))
    shoot_service.record_event(sid, ph, KIND_END, None, {"files": list(files)})


def _families(sid):
    from core.db import get_db
    with get_db() as conn:
        return [r["code"] for r in conn.execute("SELECT code FROM families WHERE school_id=?", (sid,))]


async def test_a_balanced_class_becomes_one_family_per_child(shoot_org):
    sid, org = shoot_org
    names = [f"DSC_{i:04d}.JPG" for i in range(1, 6)]
    _drop(org.incoming, *names)
    _run(sid, "3A", [(KIND_CHILD, 2), (KIND_CHILD, 3)], names)
    await org.process_pending()

    codes = _families(sid)
    assert len(codes) == 2
    counts = sorted(len(_names(sid, c)) for c in codes)
    assert counts == [2, 3]
    # The client's layout: school / class / "Student N", numbered in shooting order, no name anywhere.
    from services import photo_service
    root = photo_service.school_root(sid)
    assert sorted("/".join(_dir(sid, c).parts[len(root.parts):]) for c in codes) == ["3A/Student 1", "3A/Student 2"]
    assert not [f for f in org.incoming.iterdir() if f.is_file()]
    from core.db import get_db
    with get_db() as conn:
        assert {r["class_name"] for r in conn.execute("SELECT class_name FROM students")} >= {"3A"}


async def test_children_get_the_files_in_capture_order(shoot_org):
    sid, org = shoot_org
    names = ["DSC_0009.JPG", "DSC_0010.JPG", "DSC_0011.JPG"]       # 9 < 10 only with natural ordering
    _drop(org.incoming, *names)
    _run(sid, "3A", [(KIND_CHILD, 1), (KIND_CHILD, 2)], names)
    await org.process_pending()
    by_size = {len(_names(sid, c)): c for c in _families(sid)}
    assert _names(sid, by_size[1]) == ["DSC_0009.JPG"]
    assert set(_names(sid, by_size[2])) == {"DSC_0010.JPG", "DSC_0011.JPG"}


async def test_a_mismatch_assigns_nothing_and_does_not_shift_the_next_class(shoot_org):
    sid, org = shoot_org
    bad = [f"A_{i:04d}.JPG" for i in range(1, 6)]                  # 5 files, 4 declared
    good = [f"B_{i:04d}.JPG" for i in range(1, 3)]
    _drop(org.incoming, *bad, *good)
    _run(sid, "3A", [(KIND_CHILD, 2), (KIND_CHILD, 2)], bad)
    _run(sid, "4B", [(KIND_CHILD, 2)], good)
    await org.process_pending()

    codes = _families(sid)
    assert len(codes) == 1                                           # only 4B got a child
    assert _names(sid, codes[0]) == good
    parked = list((org.incoming / "_unassigned").rglob("*.JPG"))
    assert sorted(p.name for p in parked) == bad                     # nothing lost, nobody sees them
    assert any(k.startswith("shoot-blocked") for k in org.alerts)
    assert shoot_service.get_state(sid, PH)["blocked"][0]["class"] == "3A"


async def test_skipped_photos_are_set_aside_not_given_to_a_child(shoot_org):
    sid, org = shoot_org
    names = ["DSC_0001.JPG", "DSC_0002.JPG", "DSC_0003.JPG"]
    _drop(org.incoming, *names)
    _run(sid, "3A", [(KIND_SKIP, 1), (KIND_CHILD, 2)], names)
    await org.process_pending()
    assert [p.name for p in (org.incoming / "_ignored").iterdir()] == ["DSC_0001.JPG"]
    assert len(_families(sid)) == 1


async def test_files_of_the_open_class_are_left_alone_until_it_is_closed(shoot_org):
    sid, org = shoot_org
    shoot_service.record_event(sid, PH, KIND_CLASS, "3A", {"before": []})
    shoot_service.record_event(sid, PH, KIND_CHILD, "2")
    _drop(org.incoming, "DSC_0001.JPG", "DSC_0002.JPG", age=3600)       # old, but its class is still open
    await org.process_pending()
    assert (org.incoming / "DSC_0001.JPG").exists() and _families(sid) == []


async def test_strays_wait_then_are_parked_and_never_reach_a_family(shoot_org):
    sid, org = shoot_org
    _drop(org.incoming, "DSC_9001.JPG", age=30)                          # no class at all, recent: waits
    _drop(org.incoming, "DSC_9002.JPG", age=3600)                        # no class at all, old: parked
    await org.process_pending()
    assert (org.incoming / "DSC_9001.JPG").exists()
    assert (org.incoming / "_unassigned" / "DSC_9002.JPG").exists()
    assert _families(sid) == []
    assert any(k.startswith("shoot-unassigned") for k in org.alerts)


async def test_a_failed_move_is_retried_without_creating_a_second_family(shoot_org, monkeypatch):
    sid, org = shoot_org
    names = ["DSC_0001.JPG", "DSC_0002.JPG"]
    _drop(org.incoming, *names)
    _run(sid, "3A", [(KIND_CHILD, 2)], names)
    real_move, calls = org._move, {"n": 0}

    def flaky(src, dst):
        calls["n"] += 1
        return False if calls["n"] == 1 else real_move(src, dst)

    monkeypatch.setattr(org, "_move", flaky)
    await org.process_pending()                                           # first pass: the move fails
    await org.process_pending()                                           # second pass: it works
    codes = _families(sid)
    assert len(codes) == 1                                                # one child, one code
    assert _names(sid, codes[0]) == names


async def test_a_class_with_files_still_uploading_waits(shoot_org, monkeypatch):
    sid, org = shoot_org
    _drop(org.incoming, "DSC_0001.JPG")
    _run(sid, "3A", [(KIND_CHILD, 2)], ["DSC_0001.JPG", "DSC_0002.JPG"])     # the second file never showed up
    (org.incoming / "DSC_0002.JPG").write_bytes(b"partial")                  # exists but is not a readable image yet
    monkeypatch.setattr(O, "_filter_stable", lambda files: [f for f in files if f.name != "DSC_0002.JPG"])
    await org.process_pending()
    assert _families(sid) == [] and shoot_service.get_state(sid, PH)["processed"] == 0
