"""Photographer app, TIME mode: calibrated camera clock, one "last photo" tap per child, a doubt zone and a review
screen. The counts mode stays covered by test_shoot.py; both coexist and the school picks one."""
import io
import os
import time
from datetime import datetime, timezone
from pathlib import Path

import cv2
import segno
from PIL import Image

from core import storage
from services import photo_service, qr_detect, school_service, shoot_review_service, shoot_service, shoot_time
from services.shoot_service import KIND_CLASS, KIND_END, KIND_MARK, KIND_UNDO, build_runs
from services.shoot_time import assign_by_time

from test_shoot import PH, _post, phone, shoot_org, _families      # noqa: F401  (fixtures)


def names(res_groups):
    return {k: v for k, v in sorted(res_groups.items())}


# ── Assignment (pure) ────────────────────────────────────────────────────────────────────────────────

def test_a_photo_belongs_to_the_child_whose_tap_follows_it_and_the_end_closes_the_last_one():
    res = assign_by_time([("a", 3), ("b", 6), ("c", 14), ("d", 16), ("e", 19), ("f", 25)],
                         marks=[10, 20], doubt=3, max_per_child=3)
    assert names(res.groups) == {0: ["a", "b"], 1: ["c", "d", "e"], 2: ["f"]}
    assert not res.doubts and not res.bundles and not res.empty_marks


def test_the_order_files_arrive_in_does_not_matter_only_when_they_were_shot():
    shuffled = [("f", 25), ("a", 3), ("d", 16), ("c", 14), ("b", 6), ("e", 19)]
    res = assign_by_time(shuffled, marks=[20, 10], doubt=3, max_per_child=3)       # marks too, in any order
    assert names(res.groups) == {0: ["a", "b"], 1: ["c", "d", "e"], 2: ["f"]}


def test_a_late_file_is_placed_by_its_capture_time_even_if_it_arrives_after_the_tap():
    # 12:09 shot, arrives after the 12:10 tap: it still goes to the child that was in front of the camera at 12:09
    res = assign_by_time([("late", 9 * 60), ("x", 11 * 60 + 30)], marks=[10 * 60], doubt=3, max_per_child=3)
    assert res.groups[0] == ["late"] and res.groups[1] == ["x"]


def test_a_photo_right_after_a_tap_that_ends_a_burst_stays_with_that_burst():
    # tap at 10, the child's last shot lands at 10.5 (tap a bit early), then a long pause before the next child
    res = assign_by_time([("a", 8), ("b", 9), ("c", 10.5), ("d", 25)], marks=[10], doubt=3, max_per_child=3)
    assert res.groups[0] == ["a", "b", "c"] and res.groups[1] == ["d"] and not res.doubts


def test_a_photo_right_after_a_tap_that_starts_a_burst_goes_with_the_next_child():
    res = assign_by_time([("a", 2), ("b", 12.0), ("c", 13.0), ("d", 14.0)], marks=[10], doubt=3, max_per_child=3)
    assert res.groups[0] == ["a"] and res.groups[1] == ["b", "c", "d"] and not res.doubts


def test_a_photo_the_gaps_cannot_settle_is_never_guessed():
    res = assign_by_time([("a", 8), ("b", 9.5), ("c", 11), ("d", 13)], marks=[10], doubt=3, max_per_child=3)
    assert [d.name for d in res.doubts] == ["c"]
    assert (res.doubts[0].prev, res.doubts[0].next) == (0, 1)
    assert "c" not in sum(res.groups.values(), [])


def test_a_photo_outside_the_doubt_zone_is_certain_however_close_to_a_tap():
    res = assign_by_time([("a", 9.9), ("b", 14)], marks=[10], doubt=3, max_per_child=3)     # 14 is > 3 s after the tap
    assert res.groups == {0: ["a"], 1: ["b"]} and not res.doubts


def test_a_group_bigger_than_the_maximum_is_held_for_review_not_assigned():
    res = assign_by_time([(f"p{i}", i) for i in range(1, 6)] + [("z", 30)], marks=[10], doubt=3, max_per_child=3)
    assert res.bundles == {0: ["p1", "p2", "p3", "p4", "p5"]} and res.groups == {1: ["z"]}


def test_a_tap_with_no_photo_is_reported():
    res = assign_by_time([("a", 3), ("b", 25)], marks=[10, 11, 20], doubt=0.5, max_per_child=3)
    assert res.empty_marks == [1, 2]
    assert res.groups == {0: ["a"], 3: ["b"]}


def test_a_straggler_near_a_tap_is_doubtful_and_far_from_it_is_not():
    assert shoot_time.classify_straggler(11, [10, 20], doubt=3) == (1, True)
    assert shoot_time.classify_straggler(15, [10, 20], doubt=3) == (1, False)
    assert shoot_time.classify_straggler(5, [10, 20], doubt=3) == (0, False)
    assert shoot_time.classify_straggler(99, [10, 20], doubt=3) == (2, False)


# ── Calibration (pure) ───────────────────────────────────────────────────────────────────────────────

def test_the_calibration_qr_roundtrips_and_rejects_anything_else():
    payload = shoot_time.cal_payload("ecole-x", 1760000000.123)
    assert shoot_time.parse_cal_qr(payload) == ("ecole-x", 1760000000.123)
    for bad in ("MEEC:CLASS:ecole-x:3A", "MEEC:CAL:../x:1760000000123", "MEEC:CAL:ecole-x:12", "", None):
        assert shoot_time.parse_cal_qr(bad) is None


def test_the_camera_offset_is_camera_time_minus_real_time_and_is_undone_exactly():
    cal = shoot_time.build_calibration(shown=1000.0, camera=1013.5, now=1002.0)
    assert cal["offset"] == 13.5
    assert shoot_time.real_time([cal], 1113.5) == 1100.0
    assert shoot_time.real_time([cal], None) is None and shoot_time.real_time([], 1113.5) is None


def test_a_calibration_qr_from_the_future_or_long_ago_is_not_believed():
    import pytest
    with pytest.raises(ValueError, match="qr_future"):
        shoot_time.build_calibration(shown=2000.0, camera=2000.0, now=1000.0)
    with pytest.raises(ValueError, match="qr_old"):
        shoot_time.build_calibration(shown=1000.0, camera=1000.0, now=1000.0 + 3600)


def test_between_two_calibrations_the_clock_drift_is_interpolated():
    cals = [{"camera": 1000.0, "offset": 10.0}, {"camera": 2000.0, "offset": 20.0}]
    assert shoot_time.offset_at(cals, 1500.0) == 15.0
    assert shoot_time.offset_at(cals, 100.0) == 10.0 and shoot_time.offset_at(cals, 9999.0) == 20.0


def test_a_tap_time_that_cannot_be_true_is_replaced_by_now():
    now = time.time()
    assert abs(shoot_service.believable_tap_time(None) - now) < 2
    assert abs(shoot_service.believable_tap_time(now + 3600) - now) < 2           # phone clock far ahead
    assert abs(shoot_service.believable_tap_time(now - 99 * 3600) - now) < 2      # absurdly old
    assert abs(shoot_service.believable_tap_time("x") - now) < 2
    assert shoot_service.believable_tap_time(now - 120) == now - 120               # a tap queued offline is kept


def test_marks_are_folded_and_an_undo_takes_back_the_last_tap_of_either_kind():
    def ev(i, kind, target=None, at=0.0, **meta):
        return {"id": i, "at": at, "kind": kind, "target": target, "meta": meta}
    runs = build_runs([ev(1, KIND_CLASS, "3A", at=100.0, mode="time"), ev(2, KIND_MARK, at=110.0),
                       ev(3, KIND_MARK, at=120.0), ev(4, KIND_UNDO), ev(5, KIND_END, at=130.0)])
    r = runs[0]
    assert r.mode == "time" and r.marks == [110.0] and (r.start, r.end) == (100.0, 130.0) and r.closed and r.children == 1


# ── Helpers: photos with a capture time ──────────────────────────────────────────────────────────────

def shot(path: Path, camera_epoch: float, mtime_age: float = 120.0, size=(160, 120)):
    """A JPEG whose EXIF capture time is `camera_epoch` (read as UTC, like shoot_time does)."""
    path.parent.mkdir(parents=True, exist_ok=True)
    taken = datetime.fromtimestamp(camera_epoch, timezone.utc)
    exif = Image.Exif()
    exif[0x8769] = {36867: taken.strftime("%Y:%m:%d %H:%M:%S"), 37521: f"{taken.microsecond // 1000:03d}"}
    Image.new("RGB", size, (90, 120, 200)).save(path, "JPEG", exif=exif)
    t = time.time() - mtime_age
    os.utime(path, (t, t))


def calibrate(sid, offset=0.0):
    now = time.time()
    return shoot_time.add_cal(sid, PH, {"offset": offset, "camera": now - offset, "shown": now - 1, "at": now})


def timed_run(sid, taps, *, end, start=0.0, base=None, mode="time"):
    """A closed class as the phone records it: class at `start`, 'last photo' taps, class end. Times are offsets
    from `base` (seconds before now by default so the class is long over)."""
    base = time.time() - 600 if base is None else base
    shoot_service.record_event(sid, PH, KIND_CLASS, "3A", {"before": [], "mode": mode}, at=base + start)
    for t in taps:
        shoot_service.record_event(sid, PH, KIND_MARK, None, at=base + t)
    shoot_service.record_event(sid, PH, KIND_END, None, None, at=base + end)
    return base


def family_photos(org, sid):
    out = {}
    for code in _families(sid):
        out[code] = sorted(p.name for _l, d in photo_service.family_dirs(sid, code) for p in storage.files(d))
    return out


# ── Organizer: a class assigned by time ─────────────────────────────────────────────────────────────

async def test_a_class_is_split_between_children_by_capture_time(shoot_org):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[10, 20], end=30)
    for n, t in {"a.jpg": 2, "b.jpg": 5, "c.jpg": 14, "d.jpg": 16, "e.jpg": 18, "f.jpg": 25}.items():
        shot(org.incoming / n, base + t)
    await org.process_pending()
    groups = sorted(family_photos(org, sid).values())
    assert groups == [["a.jpg", "b.jpg"], ["c.jpg", "d.jpg", "e.jpg"], ["f.jpg"]]
    assert not [f for f in org.incoming.iterdir() if f.is_file()]


async def test_the_camera_offset_is_removed_before_photos_are_placed(shoot_org):
    sid, org = shoot_org
    calibrate(sid, offset=3600 + 17)                    # camera one hour (time zone) and 17 s ahead
    base = timed_run(sid, taps=[10], end=30)
    shot(org.incoming / "a.jpg", base + 4 + 3617)
    shot(org.incoming / "b.jpg", base + 20 + 3617)
    await org.process_pending()
    assert sorted(family_photos(org, sid).values()) == [["a.jpg"], ["b.jpg"]]


async def test_nothing_is_placed_before_the_camera_is_calibrated(shoot_org):
    sid, org = shoot_org
    base = timed_run(sid, taps=[10], end=30)
    shot(org.incoming / "a.jpg", base + 4)
    await org.process_pending()
    assert _families(sid) == [] and (org.incoming / "a.jpg").exists()          # waits, never guesses
    calibrate(sid)
    await org.process_pending()                         # once calibrated, the same photo finds its child
    assert len(_families(sid)) == 1


async def test_a_class_waits_while_files_are_still_arriving(shoot_org):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[10], end=30)
    shot(org.incoming / "a.jpg", base + 4, mtime_age=1.0)                        # arrived a second ago: FTP is busy
    await org.process_pending()
    assert _families(sid) == [] and (org.incoming / "a.jpg").exists()


async def test_a_photo_nobody_can_settle_waits_in_review_and_an_operator_places_it(shoot_org, monkeypatch):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[10], end=30)
    for n, t in {"a.jpg": 8, "b.jpg": 9.5, "c.jpg": 11, "d.jpg": 13}.items():
        shot(org.incoming / n, base + t)
    await org.process_pending()
    placed = family_photos(org, sid)
    assert sorted(placed.values()) == [["a.jpg", "b.jpg"], ["d.jpg"]]             # c.jpg was not guessed
    assert shoot_time.open_review_count(sid) == 1
    item = shoot_review_service.list_items(sid)[0]
    assert item["kind"] == "doubt" and [p["name"] for p in item["photos"]] == ["c.jpg"]
    assert not (org.incoming / "c.jpg").exists()                                   # parked where families cannot see

    out = shoot_review_service.resolve(sid, item["id"], "prev")                    # with the child before the tap
    assert len(out["codes"]) == 1 and shoot_time.open_review_count(sid) == 0
    assert sorted(family_photos(org, sid).values()) == [["a.jpg", "b.jpg", "c.jpg"], ["d.jpg"]]


async def test_a_group_too_big_is_cut_by_the_operator_into_children(shoot_org, monkeypatch):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[20], end=40)
    for i in range(4):
        shot(org.incoming / f"p{i}.jpg", base + 3 + 3 * i)
    shot(org.incoming / "z.jpg", base + 30)
    await org.process_pending()
    assert sorted(family_photos(org, sid).values()) == [["z.jpg"]]
    item = shoot_review_service.list_items(sid)[0]
    assert item["kind"] == "bundle" and len(item["photos"]) == 4

    import pytest
    with pytest.raises(shoot_review_service.ReviewError):
        shoot_review_service.resolve(sid, item["id"], "groups", [1, 1])            # must add up to the 4 photos
    shoot_review_service.resolve(sid, item["id"], "groups", [2, 2])
    assert sorted(family_photos(org, sid).values()) == [["p0.jpg", "p1.jpg"], ["p2.jpg", "p3.jpg"], ["z.jpg"]]


async def test_discarding_a_review_item_removes_it_from_the_queue_without_giving_it_to_anyone(shoot_org):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[10], end=30)
    for n, t in {"a.jpg": 8, "b.jpg": 9.5, "c.jpg": 11, "d.jpg": 13}.items():
        shot(org.incoming / n, base + t)
    await org.process_pending()
    item = shoot_review_service.list_items(sid)[0]
    shoot_review_service.resolve(sid, item["id"], "discard")
    assert shoot_time.open_review_count(sid) == 0
    assert (org.incoming / "_ignored" / "c.jpg").exists()
    assert sorted(family_photos(org, sid).values()) == [["a.jpg", "b.jpg"], ["d.jpg"]]


async def test_a_file_that_arrives_after_its_class_was_processed_still_finds_its_child(shoot_org):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[20], end=40)
    shot(org.incoming / "a.jpg", base + 5)
    shot(org.incoming / "b.jpg", base + 30)
    await org.process_pending()
    first = {tuple(v): k for k, v in family_photos(org, sid).items()}
    assert set(first) == {("a.jpg",), ("b.jpg",)}
    shot(org.incoming / "late.jpg", base + 8)                                      # FTP was down: it is for child 0
    await org.process_pending()
    assert sorted(family_photos(org, sid)[first[("a.jpg",)]]) == ["a.jpg", "late.jpg"]
    assert len(_families(sid)) == 2


async def test_a_late_file_right_at_a_tap_goes_to_review_not_to_a_guess(shoot_org):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[20], end=40)
    shot(org.incoming / "a.jpg", base + 5)
    shot(org.incoming / "b.jpg", base + 30)
    await org.process_pending()
    shot(org.incoming / "edge.jpg", base + 21)
    await org.process_pending()
    assert shoot_time.open_review_count(sid) == 1 and not (org.incoming / "edge.jpg").exists()


async def test_photos_outside_every_class_are_strays_and_never_reach_a_child(shoot_org, monkeypatch):
    sid, org = shoot_org
    calibrate(sid)
    base = timed_run(sid, taps=[10], end=30)
    shot(org.incoming / "a.jpg", base + 5)
    shot(org.incoming / "stray.jpg", base + 200, mtime_age=3600)                   # shot after the class, no class open
    await org.process_pending()
    assert (org.incoming / "_unassigned" / "stray.jpg").exists()
    assert len(_families(sid)) == 1


# ── Organizer: calibration photo ────────────────────────────────────────────────────────────────────

def calibration_photo(path: Path, school_id: str, shown: float, camera: float):
    """A photo of the phone showing the calibration QR (the QR carries `shown`), stamped by a camera at `camera`."""
    path.parent.mkdir(parents=True, exist_ok=True)
    taken = datetime.fromtimestamp(camera, timezone.utc)
    exif = Image.Exif()
    exif[0x8769] = {36867: taken.strftime("%Y:%m:%d %H:%M:%S"), 37521: f"{taken.microsecond // 1000:03d}"}
    # OpenCV's detector misses ~1 payload in 150 (the school id and the time are random: a CI flake). The payload
    # is what is under test, not the detector, so draw the same payload with the first QR mask that reads back.
    for mask in range(8):
        qr = segno.make(shoot_time.cal_payload(school_id, shown), error="m", mask=mask)
        buf = io.BytesIO()
        qr.save(buf, kind="png", scale=8, border=4)
        buf.seek(0)
        canvas = Image.new("RGB", (900, 700), (30, 30, 30))
        code = Image.open(buf).convert("RGB")
        canvas.paste(code, ((900 - code.width) // 2, (700 - code.height) // 2))
        canvas.save(path, "JPEG", exif=exif, quality=92)
        if qr_detect.detect_qr(cv2.imread(str(path)), path, set(), use_ocr=False):
            return
    raise AssertionError("no QR mask of the calibration payload is readable by the detector")


async def test_the_calibration_photo_measures_the_camera_and_is_consumed(shoot_org):
    sid, org = shoot_org
    shoot_time.open_cal_window(sid, PH)
    now = time.time()
    calibration_photo(org.incoming / "DSC_0001.JPG", sid, shown=now - 4, camera=now - 4 + 7.25)
    await org.process_pending()
    st = shoot_time.cal_status(sid, PH)
    # The status in the message: this failed once on CI (MySQL 8, Linux) and never locally; result None means the
    # QR was not seen, an error code means it was seen and rejected.
    assert st["calibrated"] and not st["waiting"], (st, sorted(p.name for p in org.incoming.rglob("*")))
    assert st["result"]["ok"] and abs(st["result"]["offset"] - 7.25) < 0.01 and st["result"]["verified"] is None
    assert (org.incoming / "_calibration" / "DSC_0001.JPG").exists() and not (org.incoming / "DSC_0001.JPG").exists()


async def test_a_second_calibration_photo_verifies_the_first(shoot_org):
    sid, org = shoot_org
    now = time.time()
    shoot_time.open_cal_window(sid, PH)
    calibration_photo(org.incoming / "DSC_0001.JPG", sid, shown=now - 60, camera=now - 60 + 5.0)
    await org.process_pending()
    shoot_time.open_cal_window(sid, PH)
    calibration_photo(org.incoming / "DSC_0002.JPG", sid, shown=now - 4, camera=now - 4 + 5.5)
    await org.process_pending()
    res = shoot_time.cal_status(sid, PH)["result"]
    assert res["verified"] is True and abs(res["drift"] - 0.5) < 0.01 and res["count"] == 2

    shoot_time.open_cal_window(sid, PH)
    calibration_photo(org.incoming / "DSC_0003.JPG", sid, shown=now - 2, camera=now - 2 + 30.0)
    await org.process_pending()
    assert shoot_time.cal_status(sid, PH)["result"]["verified"] is False           # the clock moved: do not trust it


async def test_a_calibration_photo_without_a_capture_time_is_refused_with_a_reason(shoot_org):
    sid, org = shoot_org
    shoot_time.open_cal_window(sid, PH)
    now = time.time()
    calibration_photo(org.incoming / "DSC_0009.JPG", sid, shown=now - 3, camera=now)
    # same picture the other tests use (a bare QR was not read by the detector on the CI machine), EXIF stripped
    Image.open(org.incoming / "DSC_0009.JPG").convert("RGB").save(org.incoming / "DSC_0009.JPG", "JPEG")
    await org.process_pending()
    res = shoot_time.cal_status(sid, PH)
    assert not res["calibrated"] and res["result"]["ok"] is False and res["result"]["error"] == "no_exif"


async def test_photos_are_not_scanned_for_the_calibration_qr_unless_the_phone_asked(shoot_org):
    sid, org = shoot_org
    now = time.time()
    calibration_photo(org.incoming / "DSC_0001.JPG", sid, shown=now - 4, camera=now - 4)
    school_service.update_settings(sid, {"shoot_mode": True})
    await org.process_pending()
    assert not shoot_time.cal_status(sid, PH)["calibrated"]


# ── API: the phone ──────────────────────────────────────────────────────────────────────────────────

async def _time_phone(client, phone):
    r = await client.put("/api/admin/settings", json={"settings": {"shoot_assign": "time"}}, headers=phone["admin"])
    assert r.status_code == 200, r.text


async def test_the_assignment_mode_is_a_school_choice_with_two_valid_values(client, phone):
    r = await client.put("/api/admin/settings", json={"settings": {"shoot_assign": "gps"}}, headers=phone["admin"])
    assert r.status_code == 400
    info = (await client.get("/api/shoot/info", headers=phone["tok"])).json()
    assert info["assign_mode"] == "counts" and info["doubt_secs"] == 3
    await _time_phone(client, phone)
    info = (await client.get("/api/shoot/info", headers=phone["tok"])).json()
    assert info["assign_mode"] == "time"
    fields = (await client.get("/api/admin/settings", headers=phone["admin"])).json()["fields"]
    assert next(f for f in fields if f["key"] == "shoot_assign")["choices"] == ["counts", "time"]


async def test_a_class_remembers_the_mode_it_started_in(client, phone):
    await _time_phone(client, phone)
    r = await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    assert r.json()["mode"] == "time"
    await client.put("/api/admin/settings", json={"settings": {"shoot_assign": "counts"}}, headers=phone["admin"])
    assert (await _post(client, phone, "mark")).status_code == 200                  # this class is still a time class
    assert (await _post(client, phone, "child", count=1)).status_code == 409
    await _post(client, phone, "end")
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])                # the next one is a counts class
    assert (await _post(client, phone, "mark")).status_code == 409
    assert (await _post(client, phone, "child", count=1)).status_code == 200


async def test_a_tap_sent_twice_is_recorded_once(client, phone):
    await _time_phone(client, phone)
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    first = await _post(client, phone, "mark", req="tap-1")
    again = await _post(client, phone, "mark", req="tap-1")                          # the answer was lost, phone resends
    assert first.json().get("duplicate") is None and again.json()["duplicate"] is True
    assert again.json()["live"]["children"] == 1
    assert (await _post(client, phone, "mark", req="tap-2")).json()["live"]["children"] == 2


async def test_undo_takes_back_the_last_mark(client, phone):
    await _time_phone(client, phone)
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    await _post(client, phone, "mark")
    await _post(client, phone, "mark")
    assert (await _post(client, phone, "undo")).json()["live"]["children"] == 1


async def test_a_tap_keeps_the_moment_the_phone_gave_it(client, phone):
    await _time_phone(client, phone)
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    moment = time.time() - 90                                  # queued offline for a minute and a half
    await _post(client, phone, "mark", at=moment)
    ev = [e for e in shoot_service.events_for(phone["sid"], PH) if e["kind"] == KIND_MARK][0]
    assert abs(ev["at"] - moment) < 0.01


async def test_the_server_clock_is_offered_to_the_phone(client, phone):
    r = await client.get("/api/shoot/time", headers=phone["tok"])
    assert abs(r.json()["now"] - time.time()) < 5


async def test_the_calibration_screen_asks_the_server_to_look_and_can_cancel(client, phone):
    await _time_phone(client, phone)
    r = await _post(client, phone, "calibrate")
    assert r.json()["calibration"]["waiting"] is True
    status = (await client.get("/api/shoot/status", headers=phone["tok"])).json()
    assert status["calibration"][PH]["waiting"] is True and status["review"] == 0
    r = await _post(client, phone, "calibrate", cancel=True)
    assert r.json()["calibration"]["waiting"] is False


async def test_polling_all_day_is_never_throttled_but_a_link_guesser_is(client, phone):
    for _ in range(80):
        assert (await client.get("/api/shoot/time", headers=phone["tok"])).status_code == 200
    codes = [(await client.get("/api/shoot/time", headers={"X-Shoot-Token": f"{i:040d}"})).status_code for i in range(70)]
    assert codes[0] == 401 and 429 in codes


async def test_live_time_counts_follow_the_taps_and_the_photos_received(client, phone):
    await _time_phone(client, phone)
    calibrate(phone["sid"])
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    now = time.time()
    shot(phone["folder"] / "a.jpg", now + 0.5, mtime_age=0)
    shot(phone["folder"] / "b.jpg", now + 1.0, mtime_age=0)
    live = (await _post(client, phone, "mark", at=now + 2)).json()["live"]
    assert live["mode"] == "time" and live["calibrated"] and live["children"] == 1
    assert live["received"] == 2 and live["last_group"] == 2 and live["ok"] is True


async def test_an_uncalibrated_camera_is_flagged_on_the_phone(client, phone):
    await _time_phone(client, phone)
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    live = (await _post(client, phone, "mark")).json()["live"]
    assert live["calibrated"] is False and live["ok"] is False


async def test_the_review_screen_serves_signed_previews_and_settles_items(client, phone):
    await _time_phone(client, phone)
    sid = phone["sid"]
    rid = shoot_time.add_review(sid, PH, 1, "3A", "doubt", [{"name": "c.jpg", "t": 1.0}], 0, 1)
    d = shoot_review_service.review_dir(sid, rid)
    shot(d / "c.jpg", time.time())
    items = (await client.get("/api/admin/shoot/review", headers=phone["admin"])).json()["items"]
    assert len(items) == 1 and items[0]["photos"][0]["name"] == "c.jpg"
    img = await client.get(items[0]["photos"][0]["url"])
    assert img.status_code == 200 and img.headers["content-type"] == "image/webp"
    assert (await client.get(items[0]["photos"][0]["url"].replace("sig=", "sig=0"))).status_code == 403
    r = await client.post(f"/api/admin/shoot/review/{rid}", json={"action": "next"}, headers=phone["admin"])
    assert r.status_code == 200 and len(r.json()["codes"]) == 1
    assert (await client.get("/api/admin/shoot/review", headers=phone["admin"])).json()["items"] == []
    again = await client.post(f"/api/admin/shoot/review/{rid}", json={"action": "next"}, headers=phone["admin"])
    assert again.status_code == 409


async def test_the_review_screen_belongs_to_the_operator_of_that_school(client, phone):
    r = await client.get("/api/admin/shoot/review")
    assert r.status_code in (401, 403)


# ── The phone as the camera, and what "no readable capture time" really means ─────────────────────────

async def test_with_the_phone_standing_in_for_the_camera_there_is_nothing_to_calibrate(shoot_org):
    sid, org = shoot_org
    school_service.update_settings(sid, {"shoot_test_camera": True})                  # no calibration photo was taken
    base = timed_run(sid, taps=[10], end=30)
    shot(org.incoming / "a.jpg", base + 4)
    shot(org.incoming / "b.jpg", base + 20)
    await org.process_pending()
    assert sorted(family_photos(org, sid).values()) == [["a.jpg"], ["b.jpg"]]


async def test_a_missing_calibration_is_not_reported_as_photos_without_a_capture_time(client, phone):
    await _time_phone(client, phone)
    await _post(client, phone, "class", qr=phone["classes"][0]["qr"])
    now = time.time()
    shot(phone["folder"] / "with_exif.jpg", now, mtime_age=0)
    Image.new("RGB", (40, 40), "white").save(phone["folder"] / "no_exif.jpg", "JPEG")
    live = (await _post(client, phone, "mark")).json()["live"]
    assert live["calibrated"] is False and live["unread"] == 1          # only the file that really has no time
    await client.put("/api/admin/settings", json={"settings": {"shoot_test_camera": True}}, headers=phone["admin"])
    live = (await _post(client, phone, "mark")).json()["live"]
    assert live["calibrated"] is True and live["unread"] == 1 and live["received"] == 1


# ── "Class not assigned" notices: recent, and the photographer can dismiss them ───────────────────────

async def test_an_old_class_not_assigned_notice_does_not_haunt_the_phone(client, phone):
    sid = phone["sid"]
    now = time.time()
    shoot_service.set_state(sid, PH, {"processed": 0, "blocked": [
        {"run": 1, "class": "2A", "declared": 1, "received": 0, "reason": "x"},                       # no timestamp: old
        {"run": 2, "class": "3A", "declared": 2, "received": 0, "reason": "x", "at": now - 8 * 3600},   # too old
        {"run": 3, "class": "4B", "declared": 3, "received": 1, "reason": "x", "at": now - 60},        # recent
    ]})
    shown = (await client.get("/api/shoot/status", headers=phone["tok"])).json()["blocked"][PH]
    assert [b["class"] for b in shown] == ["4B"]
    r = await _post(client, phone, "ack-blocked")
    assert r.json()["blocked"] == []
    assert (await client.get("/api/shoot/status", headers=phone["tok"])).json()["blocked"][PH] == []
