"""
shoot_time.py — the "time" way of finding a photo's child (school setting `shoot_assign = time`).

The counts way (shoot_service.py) trusts what the photographer declares. This one trusts the camera's clock — but
only after it has been MEASURED against the server, and never where a clock cannot be trusted:

  * CALIBRATION. The phone shows a QR that carries the server time (`MEEC:CAL:{school}:{ms}`). The photographer
    shoots it with the real camera once. The organizer reads the QR and the photo's EXIF time; the difference is the
    camera's offset (clock error AND time zone, both absorbed — EXIF has no zone). Nothing has to be set on the
    camera, and it can be repeated at any moment: a second photo also VERIFIES the first (drift between the two).
  * ONE TAP PER CHILD, "last photo of this child", tapped right after the last shot. Photo time T belongs to the
    child whose tap is the first one at or after T; the end of the class is the final tap. FTP delay is irrelevant
    because the CAPTURE time is used, never the arrival time — a late file lands where it belongs.
  * NO GUESSING NEAR A TAP. A photo within `shoot_doubt_secs` AFTER a tap could be the end of the previous child
    (tap too early) or the start of the next one. It is settled only when the gaps between shots make it obvious
    (a burst on one side, a pause on the other); otherwise it goes to the REVIEW screen. A group bigger than
    `shoot_max_per_child` is never assigned either (that is how two children end up on one code): it is reviewed.
  * Faces are never compared (biometric data of minors); nothing here looks at pixels except the calibration QR.

The functions in the first half are pure on purpose: they are what the tests pin down.
"""
import json
import logging
import re
import time
from bisect import bisect_left
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

from core.db import get_db, ensure_column, TABLE_OPTIONS
from core.timeutil import utcnow_iso

logger = logging.getLogger("meeconic.shoot")

ASSIGN_COUNTS, ASSIGN_TIME = "counts", "time"
SETTLE_SECS = 45.0            # a closed class is processed once nothing new has arrived for this long
CAL_WINDOW_SECS = 600         # how long the organizer looks for the calibration photo after the phone asks
CAL_MAX_AGE_SECS = 20 * 60    # a calibration QR older than this when photographed is a screenshot, not the screen
CAL_VERIFY_TOLERANCE = 2.0    # two calibrations that differ by more than this: the clock moved or a photo is off
GAP_RATIO = 2.5               # one gap must be this many times smaller than the other to settle a doubtful photo
GAP_FLOOR = 3.0               # ...and the larger gap at least this long (seconds)

# Case-insensitive: a QR written in the compact alphanumeric mode comes back in capitals.
_CAL_RE = re.compile(r"^MEEC:CAL:([a-z0-9][a-z0-9-]{0,63}):(\d{10,16})$", re.I)


# ── Calibration QR and clock arithmetic (pure) ───────────────────────────────────────────────────────────────

def cal_payload(school_id: str, ts: float) -> str:
    return f"MEEC:CAL:{school_id}:{int(round(ts * 1000))}"


def parse_cal_qr(text: Optional[str]) -> Optional[tuple[str, float]]:
    """(school_id, server time in seconds) or None. Anything that is not exactly a calibration QR is ignored."""
    m = _CAL_RE.match((text or "").strip())
    return (m.group(1).lower(), int(m.group(2)) / 1000.0) if m else None


def exif_epoch(dt: datetime) -> float:
    """EXIF times carry no zone: read them as UTC. The zone is then part of the camera offset, which is measured."""
    return dt.replace(tzinfo=timezone.utc).timestamp()


def capture_epoch(path: Path) -> Optional[float]:
    """The camera's capture time of a file, as `exif_epoch`, with sub-seconds when the camera writes them."""
    try:
        from PIL import Image
        with Image.open(path) as img:
            exif = img.getexif()
            if not exif:
                return None
            sub = exif.get_ifd(0x8769) if hasattr(exif, "get_ifd") else {}
            raw = sub.get(36867) or sub.get(36868) or exif.get(306)
            if not raw:
                return None
            base = exif_epoch(datetime.strptime(str(raw).strip(), "%Y:%m:%d %H:%M:%S"))
            frac = str(sub.get(37521) or sub.get(37522) or "").strip()
            if frac.isdigit():
                base += float("0." + frac)
            return base
    except Exception:
        return None


def build_calibration(shown: float, camera: float, now: float) -> dict:
    """The measurement taken from ONE photo of the calibration QR. Raises ValueError (a code) if it is not credible."""
    if shown > now + 5:
        raise ValueError("qr_future")
    if now - shown > CAL_MAX_AGE_SECS:
        raise ValueError("qr_old")
    return {"offset": camera - shown, "camera": camera, "shown": shown, "at": now}


def offset_at(cals: list[dict], camera_time: float) -> Optional[float]:
    """The camera offset to apply to a photo taken at `camera_time` (camera clock). Between two calibrations the
    drift is interpolated; outside them the nearest one is used. None = never calibrated."""
    pts = sorted(((c["camera"], c["offset"]) for c in cals), key=lambda x: x[0])
    if not pts:
        return None
    if camera_time <= pts[0][0]:
        return pts[0][1]
    if camera_time >= pts[-1][0]:
        return pts[-1][1]
    for (t0, o0), (t1, o1) in zip(pts, pts[1:]):
        if t0 <= camera_time <= t1:
            return o0 if t1 == t0 else o0 + (o1 - o0) * (camera_time - t0) / (t1 - t0)
    return pts[-1][1]


def real_time(cals: list[dict], camera_time: Optional[float]) -> Optional[float]:
    """A photo's capture time on the server clock, or None (never calibrated / no EXIF time)."""
    if camera_time is None:
        return None
    off = offset_at(cals, camera_time)
    return None if off is None else camera_time - off


# ── Assignment by time (pure) ─────────────────────────────────────────────────────────────────────────────

@dataclass
class Doubt:
    name: str
    prev: int         # child that ends at the tap just before the photo
    next: int         # child that starts after it


@dataclass
class TimeResult:
    groups: dict[int, list[str]] = field(default_factory=dict)      # child index -> photos, in shot order (certain)
    doubts: list[Doubt] = field(default_factory=list)               # settled by nobody: the review screen
    bundles: dict[int, list[str]] = field(default_factory=dict)     # child index -> photos, group too big
    empty_marks: list[int] = field(default_factory=list)            # a tap with no photo (double tap?)


def assign_by_time(photos: list[tuple[str, float]], marks: list[float], *, doubt: float,
                   max_per_child: int) -> TimeResult:
    """Child `i` owns the photos with `marks[i-1] < t <= marks[i]`; the last child owns what follows the last tap
    (the end of the class acts as its tap). `photos` = (name, capture time on the server clock)."""
    marks = sorted(marks)
    ps = sorted(photos, key=lambda p: (p[1], p[0]))
    idx: dict[str, int] = {}
    near: list[int] = []                      # positions in `ps` that sit just after a tap
    for k, (name, t) in enumerate(ps):
        i = bisect_left(marks, t)
        idx[name] = i
        if i > 0 and t - marks[i - 1] <= doubt:
            near.append(k)

    unresolved: list[Doubt] = []
    for k in near:                            # in shot order: a settled neighbour helps the next one
        name, t = ps[k]
        i = idx[name]
        # A child index never goes down as time goes up, so the photo can only be one of the two children around
        # the tap AND must sit between its neighbours: a photo between two shots of the same child is theirs.
        lo = idx[ps[k - 1][0]] if k > 0 else i - 1
        hi = idx[ps[k + 1][0]] if k + 1 < len(ps) else i
        options = [c for c in (i - 1, i) if lo <= c <= hi]
        if len(options) == 1:
            idx[name] = options[0]
            continue
        gap_prev = t - ps[k - 1][1] if k > 0 else float("inf")
        gap_next = ps[k + 1][1] - t if k + 1 < len(ps) else float("inf")
        if k > 0 and gap_next >= GAP_FLOOR and gap_prev * GAP_RATIO <= gap_next:
            idx[name] = idx[ps[k - 1][0]]     # a burst with the photo before it, then a pause
        elif k + 1 < len(ps) and gap_prev >= GAP_FLOOR and gap_next * GAP_RATIO <= gap_prev:
            idx[name] = idx[ps[k + 1][0]]     # a pause, then a burst with the photo after it
        else:
            unresolved.append(Doubt(name, i - 1, i))

    held = {d.name for d in unresolved}
    res = TimeResult(doubts=unresolved)
    for name, _t in ps:
        if name not in held:
            res.groups.setdefault(idx[name], []).append(name)
    for i in sorted(res.groups):
        if len(res.groups[i]) > max_per_child:
            res.bundles[i] = res.groups.pop(i)
    res.empty_marks = [i for i in range(len(marks))
                       if not res.groups.get(i) and not res.bundles.get(i)
                       and not any(d.next == i or d.prev == i for d in unresolved)]
    return res


def classify_straggler(t: float, marks: list[float], *, doubt: float) -> tuple[int, bool]:
    """(child index, doubtful) for ONE late file of an already processed class. No neighbours are known, so
    anything near a tap is doubtful."""
    marks = sorted(marks)
    i = bisect_left(marks, t)
    return i, bool(i > 0 and t - marks[i - 1] <= doubt)


# ── Calibration state (per photographer) ───────────────────────────────────────────────────────────────────

def _kv_get(key: str) -> Optional[str]:
    with get_db() as conn:
        row = conn.execute("SELECT value FROM app_kv WHERE key=?", (key,)).fetchone()
    return row["value"] if row else None


def _kv_set(key: str, value: str) -> None:
    with get_db() as conn:
        conn.execute("INSERT OR REPLACE INTO app_kv (key, value) VALUES (?,?)", (key, value))
        conn.commit()


def _json(raw: Optional[str], default):
    try:
        return json.loads(raw) if raw else default
    except ValueError:
        return default


def get_cals(school_id: str, photographer: str) -> list[dict]:
    return _json(_kv_get(f"shoot_cal:{school_id}:{photographer}"), [])


def effective_cals(school_id: str, photographer: str) -> list[dict]:
    """The calibrations to apply. With the phone standing in for the camera (setting `shoot_test_camera`) there is
    nothing to calibrate: its photos are stamped with the server's own clock, so the offset is exactly 0."""
    cals = get_cals(school_id, photographer)
    if cals:
        return cals
    from services import school_service
    if school_service.get_settings(school_id).get("shoot_test_camera") == "true":
        return [{"offset": 0.0, "camera": 0.0, "shown": 0.0, "at": 0.0, "implicit": True}]
    return []


def add_cal(school_id: str, photographer: str, cal: dict) -> dict:
    """Store a measurement and return the RESULT the phone shows: the offset, and — when there was an earlier
    calibration — whether the two agree (that is the verification)."""
    cals = get_cals(school_id, photographer)
    prev = cals[-1] if cals else None
    cals = (cals + [cal])[-10:]
    _kv_set(f"shoot_cal:{school_id}:{photographer}", json.dumps(cals))
    result = {"ok": True, "at": cal["at"], "offset": round(cal["offset"], 3), "error": None,
              "drift": None, "verified": None, "count": len(cals)}
    if prev is not None:
        drift = cal["offset"] - prev["offset"]
        result["drift"] = round(drift, 3)
        result["verified"] = abs(drift) <= CAL_VERIFY_TOLERANCE
    result["suspicious"] = abs(cal["offset"]) > 36 * 3600     # a date wrong by days, not a time zone
    set_cal_result(school_id, photographer, result)
    return result


def set_cal_result(school_id: str, photographer: str, result: dict) -> None:
    _kv_set(f"shoot_calres:{school_id}:{photographer}", json.dumps(result))


def cal_status(school_id: str, photographer: str) -> dict:
    """What the phone shows: is a calibration being waited for, and how did the last one go."""
    win = _json(_kv_get(f"shoot_calwin:{school_id}:{photographer}"), {})
    return {"waiting": bool(win.get("until", 0) > time.time()),
            "calibrated": bool(effective_cals(school_id, photographer)),
            "result": _json(_kv_get(f"shoot_calres:{school_id}:{photographer}"), None)}


def open_cal_window(school_id: str, photographer: str) -> None:
    _kv_set(f"shoot_calwin:{school_id}:{photographer}", json.dumps({"since": time.time(), "until": time.time() + CAL_WINDOW_SECS}))


def close_cal_window(school_id: str, photographer: str) -> None:
    _kv_set(f"shoot_calwin:{school_id}:{photographer}", json.dumps({"since": 0, "until": 0}))


def cal_window(school_id: str, photographer: str) -> Optional[dict]:
    win = _json(_kv_get(f"shoot_calwin:{school_id}:{photographer}"), {})
    return win if win.get("until", 0) > time.time() else None


# ── Photo times of a folder (cached: the phone polls every few seconds) ───────────────────────────────────────

_TIME_CACHE: dict[tuple[str, int, int], Optional[float]] = {}


def capture_epoch_cached(path: Path) -> Optional[float]:
    try:
        st = path.stat()
    except OSError:
        return None
    key = (str(path), int(st.st_mtime), st.st_size)
    if key not in _TIME_CACHE:
        if len(_TIME_CACHE) > 4000:
            _TIME_CACHE.clear()
        _TIME_CACHE[key] = capture_epoch(path)
    return _TIME_CACHE[key]


# ── Review (photos nobody can place with certainty) ─────────────────────────────────────────────────────────

def init_review_table() -> None:
    with get_db() as conn:
        conn.execute(f"""
        CREATE TABLE IF NOT EXISTS shoot_review (
            id           BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            school_id    VARCHAR(64) NOT NULL,
            photographer VARCHAR(64) NOT NULL,
            run_id       BIGINT NOT NULL,
            class_name   VARCHAR(64) NOT NULL,
            kind         VARCHAR(12) NOT NULL,
            photos       MEDIUMTEXT NOT NULL,
            cand_prev    INT,
            cand_next    INT,
            status       VARCHAR(10) NOT NULL DEFAULT 'open',
            created_at   VARCHAR(40) NOT NULL,
            resolved_at  VARCHAR(40),
            KEY idx_shoot_review (school_id, status, id)
        ) {TABLE_OPTIONS}""")
        ensure_column(conn, "shoot_review", "cand_prev", "INT")
        ensure_column(conn, "shoot_review", "cand_next", "INT")
        conn.commit()


def add_review(school_id: str, photographer: str, run_id: int, class_name: str, kind: str,
               photos: list[dict], cand_prev: Optional[int] = None, cand_next: Optional[int] = None) -> int:
    """`kind`: "doubt" (one photo, two candidate children) or "bundle" (a group too big to be one child).
    `photos`: [{"name", "t"}] in shot order, files already moved to incoming/_review/{id}/ by the organizer."""
    with get_db() as conn:
        cur = conn.execute(
            "INSERT INTO shoot_review (school_id, photographer, run_id, class_name, kind, photos, cand_prev, cand_next, "
            "status, created_at) VALUES (?,?,?,?,?,?,?,?,'open',?)",
            (school_id, photographer, run_id, class_name, kind, json.dumps(photos), cand_prev, cand_next, utcnow_iso()))
        conn.commit()
        return cur.lastrowid


def open_review_count(school_id: str) -> int:
    with get_db() as conn:
        return conn.execute("SELECT COUNT(*) AS n FROM shoot_review WHERE school_id=? AND status='open'",
                            (school_id,)).fetchone()["n"]


def list_review(school_id: str) -> list[dict]:
    with get_db() as conn:
        rows = conn.execute("SELECT * FROM shoot_review WHERE school_id=? AND status='open' ORDER BY id",
                            (school_id,)).fetchall()
    out = []
    for r in rows:
        out.append({"id": r["id"], "photographer": r["photographer"], "run_id": r["run_id"],
                    "class_name": r["class_name"], "kind": r["kind"], "photos": _json(r["photos"], []),
                    "cand_prev": r["cand_prev"], "cand_next": r["cand_next"], "created_at": r["created_at"]})
    return out


def get_review(school_id: str, review_id: int) -> Optional[dict]:
    return next((r for r in list_review(school_id) if r["id"] == review_id), None)


def close_review(school_id: str, review_id: int) -> None:
    with get_db() as conn:
        conn.execute("UPDATE shoot_review SET status='done', resolved_at=? WHERE id=? AND school_id=?",
                     (utcnow_iso(), review_id, school_id))
        conn.commit()


# ── Per-run bookkeeping: which family code each child of a time-mode class got ──────────────────────────────

def get_tprog(school_id: str, photographer: str, run_id: int) -> dict:
    return _json(_kv_get(f"shoot_tprog:{school_id}:{photographer}:{run_id}"), {"codes": {}, "done": False, "flags": []})


def set_tprog(school_id: str, photographer: str, run_id: int, prog: dict) -> None:
    _kv_set(f"shoot_tprog:{school_id}:{photographer}:{run_id}", json.dumps(prog))
