"""
shoot_review_service.py — the review screen of the time mode (see shoot_time.py).

The organizer parks photos it could not place with certainty in incoming/_review/{id}/ and opens an item:
  * "doubt"  — ONE photo that sits just after a "last photo" tap: it ends the previous child or starts the next.
  * "bundle" — a group bigger than `shoot_max_per_child`: probably two children whose tap was missed.
Nobody but the operator sees those photos until a decision is made, and every decision is audited. The operator
settles an item with one click ("with the previous child" / "with the next one" / "discard", or the cut points of a
bundle). The goal of the design is that this screen stays almost empty: the doubt zone only catches what a clock
cannot settle on its own.
"""
import logging
import re
import shutil
from pathlib import Path
from typing import Optional

from PIL import Image, ImageOps

from core import storage
from core.security import sign, verify_signature
from services import photo_service, shoot_service, shoot_time

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

PREVIEW_PX = 640
_SAFE_NAME = re.compile(r"^[^/\\\x00]{1,200}$")


class ReviewError(ValueError):
    pass


def review_dir(school_id: str, review_id: int) -> Path:
    from services.organizer_service import incoming_dir_for
    return incoming_dir_for(school_id) / "_review" / str(int(review_id))


def photo_url(school_id: str, review_id: int, name: str) -> str:
    from urllib.parse import quote
    exp, sig = sign(f"review:{school_id}/{int(review_id)}/{name}", 3600)
    return f"/api/media/review/{school_id}/{int(review_id)}/{quote(name)}?exp={exp}&sig={sig}"


def preview_path(school_id: str, review_id: int, name: str, exp: int, sig: str) -> Optional[Path]:
    """A reduced copy of a parked photo for the operator (no face protection: staff only), or None."""
    if not verify_signature(f"review:{school_id}/{int(review_id)}/{name}", exp, sig) or not _SAFE_NAME.match(name):
        return None
    src = review_dir(school_id, review_id) / name
    if name.startswith(".") or not src.is_file():
        return None
    dst = src.parent / f".{src.stem}.rv{PREVIEW_PX}.webp"
    try:
        if dst.exists() and dst.stat().st_mtime >= src.stat().st_mtime:
            return dst
        with Image.open(src) as im:
            im = ImageOps.exif_transpose(im)
            im.thumbnail((PREVIEW_PX, PREVIEW_PX), Image.LANCZOS)
            tmp = dst.with_suffix(".tmp")
            im.convert("RGB").save(tmp, format="WEBP", quality=78)
            tmp.replace(dst)
        return dst
    except Exception as exc:
        logger.warning("Review preview impossible %s: %s", src, exc)
        return None


def _candidate(school_id: str, item: dict, idx: Optional[int]) -> Optional[dict]:
    """Who a candidate child is: its family code if one exists already (else a new one would be created)."""
    if idx is None or idx < 0:
        return None
    prog = shoot_time.get_tprog(school_id, item["photographer"], item["run_id"])
    code = prog.get("codes", {}).get(str(idx))
    return {"index": idx, "code": code}


def list_items(school_id: str) -> list[dict]:
    out = []
    for it in shoot_time.list_review(school_id):
        d = review_dir(school_id, it["id"])
        present = {f.name for f in d.iterdir() if f.is_file() and not f.name.startswith(".")} if d.is_dir() else set()
        photos = [{"name": p["name"], "t": p.get("t"), "url": photo_url(school_id, it["id"], p["name"])}
                  for p in it["photos"] if p["name"] in present]
        out.append({"id": it["id"], "kind": it["kind"], "class_name": it["class_name"],
                    "photographer": it["photographer"], "created_at": it["created_at"], "photos": photos,
                    "prev": _candidate(school_id, it, it["cand_prev"]), "next": _candidate(school_id, it, it["cand_next"])})
    return out


def _unique(path: Path) -> Path:
    p, n = path, 1
    while p.exists():
        p = path.parent / f"{path.stem}_{n}{path.suffix}"
        n += 1
    return p


def _place(school_id: str, photographer: str, code: str, src: Path, class_name: Optional[str] = None) -> None:
    folder = photo_service.child_dir(school_id, code, class_name, photographer)
    if folder is None:                                   # cannot happen (the code was made for this class)
        raise ReviewError(f"Family {code} is unknown.")
    dest = photo_service.unique_name(school_id, code, folder, src.name)
    storage.ingest(src, dest)          # an exception propagates: the item stays open and the photo in incoming


def _child_code(school_id: str, item: dict, idx: int) -> str:
    """The family code of child `idx` of the class, creating it if that child had no photo placed with certainty."""
    prog = shoot_time.get_tprog(school_id, item["photographer"], item["run_id"])
    code = prog.setdefault("codes", {}).get(str(idx))
    if not code:
        code = shoot_service.create_child_family(school_id, item["class_name"])
        prog["codes"][str(idx)] = code
        shoot_time.set_tprog(school_id, item["photographer"], item["run_id"], prog)
    return code


def resolve(school_id: str, review_id: int, action: str, groups: Optional[list[int]] = None) -> dict:
    """Settle one item. Raises ReviewError for anything inconsistent (nothing is moved in that case)."""
    item = shoot_time.get_review(school_id, review_id)
    if item is None:
        raise ReviewError("This review item does not exist or was already settled.")
    d = review_dir(school_id, review_id)
    files = [d / p["name"] for p in item["photos"] if _SAFE_NAME.match(p["name"]) and (d / p["name"]).is_file()]
    if not files:
        shoot_time.close_review(school_id, review_id)          # the photos are gone: nothing left to decide
        return {"moved": 0, "codes": []}
    codes: list[str] = []
    if action == "discard":
        ignored = d.parent.parent / "_ignored"
        ignored.mkdir(parents=True, exist_ok=True)
        for f in files:
            shutil.move(str(f), str(_unique(ignored / f.name)))
    elif action in ("prev", "next"):
        if item["kind"] != "doubt":
            raise ReviewError("Only a single doubtful photo is settled with the previous or the next child.")
        idx = item["cand_prev"] if action == "prev" else item["cand_next"]
        if idx is None or idx < 0:
            raise ReviewError("There is no such child in this class.")
        code = _child_code(school_id, item, idx)
        codes.append(code)
        for f in files:
            _place(school_id, item["photographer"], code, f, item["class_name"])
    elif action == "groups":
        sizes = [int(n) for n in (groups or [])]
        if not sizes or any(n < 1 for n in sizes) or sum(sizes) != len(files):
            raise ReviewError(f"The groups must add up to the {len(files)} photo(s) of this item.")
        pos = 0
        for n in sizes:
            code = shoot_service.create_child_family(school_id, item["class_name"])
            codes.append(code)
            for f in files[pos:pos + n]:
                _place(school_id, item["photographer"], code, f, item["class_name"])
            pos += n
    else:
        raise ReviewError("Unknown action.")
    for stale in d.glob(".*.webp"):                             # cached previews of the files that left
        stale.unlink(missing_ok=True)
    try:
        d.rmdir()
    except OSError:
        pass
    shoot_time.close_review(school_id, review_id)
    photo_service.invalidate_families_cache(school_id)
    return {"moved": len(files), "codes": codes}
