"""
upload_service.py — manual loading of the photos, class by class (client brief 2026-10-21, sheet 5).

No more photographer on the tool, no more FTP: Jonathan and Raphaël create the classes and a special "Siblings"
folder, then upload the ready photos by hand.
  * One class = one folder. A photo uploaded to a class that is not validated yet WAITS in staging
    (`photos/.staging/{school}/{class}/`, see photo_service) and can still be removed.
  * "Validate the class" turns every waiting photo into a pupil card ("3A · Student 4") with its code: a family, the
    class attached to it and its `{Class}/Student N` folder, numbered in file-name order (the camera's order).
  * A photo added to a class AFTER validation (a pupil absent on photo day) becomes a pupil card at once, and the
    Journal says so.
  * Anything uploaded to "Siblings" is a sibling photo: it is filed at once as a card of its own ("Siblings · Photo 4")
    that the operator then merges into the family of the children on it (family_service.merge).
  * A child may have SEVERAL photos (client, 2026-10-22). Waiting photos get a child number: photos with the same number
    become ONE card (one code, one `Student N` folder), a photo with none is a child of its own. The operator types the
    numbers, or says "3 photos per child" and the file order does the rest (the camera shoots a child's photos in a row).
    After validation, a photo can be added to an existing child by its Student number.
A duplicate (same pixels bytes already in the class) is ignored with a clear message, a file that is not a picture or
is too large is refused with its reason, and one bad file never stops the others (the browser sends them one by one).
No name is asked for or stored anywhere: a card is a class and a number.
"""
import hashlib
import io
import logging
import re
from typing import Optional

from PIL import Image

from core import config, storage
from core.db import TABLE_OPTIONS, ensure_column, get_db, named_lock
from core.security import sign, verify_signature
from core.storage import Key
from core.timeutil import utcnow_iso
from services import media_service, photo_service, school_service
from utils.code_generator import generate_unique_code

log = logging.getLogger("meeconic.upload")

# The special folder. Stored as a class (so the layout, the numbering and the sheets all work as for a class) flagged
# `kind='siblings'`; the interface calls it "Siblings" / "Fratries".
SIBLINGS_NAME = "Fratries"
ALLOWED_EXT = (".jpg", ".jpeg", ".png", ".webp")
_BAD = re.compile(r'[\\/:*?"<>|\x00-\x1f]+')


class UploadError(ValueError):
    """A refusal with a reason that is safe to show the operator."""


def init_tables() -> None:
    with get_db() as conn:
        # `kind`: 'class' | 'siblings'. `validated_at`: set when the operator validates the class.
        ensure_column(conn, "school_classes", "kind", "VARCHAR(10) NOT NULL DEFAULT 'class'")
        ensure_column(conn, "school_classes", "validated_at", "VARCHAR(40)")
        conn.execute(f"""
        CREATE TABLE IF NOT EXISTS class_uploads (
            id          INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            school_id   VARCHAR(64)  NOT NULL,
            class_name  VARCHAR(100) NOT NULL,
            filename    VARCHAR(200) NOT NULL,
            sha256      CHAR(64)     NOT NULL,
            size        INT          NOT NULL,
            state       VARCHAR(8)   NOT NULL DEFAULT 'staged',
            family_code VARCHAR(32),
            created_at  VARCHAR(40)  NOT NULL,
            created_by  VARCHAR(40),
            child_no    INT,
            KEY idx_uploads_class (school_id, class_name, state),
            KEY idx_uploads_hash (school_id, class_name, sha256)
        ) {TABLE_OPTIONS}""")
        ensure_column(conn, "class_uploads", "child_no", "INT")        # tables made before photos could be grouped
        conn.commit()


# ── Classes and the Siblings folder ─────────────────────────────────────────────────────────────

def siblings_class(school_id: str) -> dict:
    """The school's Siblings folder, created the first time it is needed."""
    with get_db() as conn:
        row = conn.execute("SELECT * FROM school_classes WHERE school_id=? AND kind='siblings'", (school_id,)).fetchone()
        if row is None:
            taken = conn.execute("SELECT 1 FROM school_classes WHERE school_id=? AND name=?",
                                 (school_id, SIBLINGS_NAME)).fetchone()
            name = SIBLINGS_NAME if not taken else f"{SIBLINGS_NAME} (photos)"
            conn.execute("INSERT INTO school_classes (school_id, name, kind) VALUES (?,?,'siblings')", (school_id, name))
            conn.commit()
            row = conn.execute("SELECT * FROM school_classes WHERE school_id=? AND kind='siblings'", (school_id,)).fetchone()
    return dict(row)


def siblings_names(school_id: str) -> set[str]:
    with get_db() as conn:
        return {r["name"] for r in conn.execute(
            "SELECT name FROM school_classes WHERE school_id=? AND kind='siblings'", (school_id,))}


def get_class(school_id: str, class_id: int) -> dict:
    with get_db() as conn:
        row = conn.execute("SELECT * FROM school_classes WHERE id=? AND school_id=?", (class_id, school_id)).fetchone()
    if not row:
        raise LookupError("Class not found.")
    return dict(row)


def class_counts(school_id: str) -> dict[str, dict]:
    """{class name: {"staged": n, "filed": n, "children": n, "foldered": bool}} — what is waiting, what is already a
    card, and how many pupils' folders really hold a photo (`foldered`: the class has pupils' folders at all; the old
    card mode typed cards by hand and has none).

    `filed` is counted in the pupils' folders, not from the upload rows: those stay behind when a card is deleted,
    merged or purged (production 2026-10-24: "CP/CE1 · 0 children · 7 photos" and an empty folder). One walk of the
    school (the bucket answers it from its MySQL index); only the originals in `{Class}/Student N/` count."""
    out: dict[str, dict] = {}
    with get_db() as conn:
        for r in conn.execute("SELECT class_name, COUNT(*) AS n FROM class_uploads WHERE school_id=? AND state='staged' "
                              "GROUP BY class_name", (school_id,)):
            _blank(out, r["class_name"])["staged"] = r["n"]
        by_dir = {r["class_dir"]: r["class_name"] for r in conn.execute(
            "SELECT DISTINCT class_dir, class_name FROM child_folders WHERE school_id=?", (school_id,))}
    for name in by_dir.values():
        _blank(out, name)["foldered"] = True
    if by_dir:
        kids: set = set()
        for f in storage.walk(photo_service.school_root(school_id)):
            rel = f.key.parts[2:]                                    # (class folder, "Student N", file)
            if (len(rel) == 3 and rel[0] in by_dir and photo_service._STUDENT_RE.match(rel[1])
                    and photo_service.is_image(f.name) and not f.name.startswith(".")
                    and photo_service.photo_kind(f.name) == "original"):
                _blank(out, by_dir[rel[0]])["filed"] += 1
                kids.add(rel[:2])
        for class_dir, _student in kids:                             # a pupil = a folder that still holds a photo
            out[by_dir[class_dir]]["children"] += 1
    return out


def _blank(out: dict, name: str) -> dict:
    return out.setdefault(name, {"staged": 0, "filed": 0, "children": 0, "foldered": False})


def rename_class(conn, school_id: str, old: str, new: str) -> None:
    """A renamed class keeps its waiting photos (inside the caller's transaction): their rows and their staging
    folder follow the name (they used to stay under the old one and vanish from the class). File by file: two class
    names can share a folder name, and the staged names carry their upload id, so they never collide. A failed move
    puts back what was moved and raises: the caller's transaction rolls back."""
    src = storage.key("photos", photo_service.STAGING_DIRNAME, school_id, photo_service.class_dirname(old))
    dst = storage.key("photos", photo_service.STAGING_DIRNAME, school_id, photo_service.class_dirname(new))
    moved = []
    if src != dst and storage.is_dir(src):
        try:
            for f in storage.files(src):
                storage.move(f.key, dst / f.name)
                moved.append(f.name)
        except Exception:
            for name in moved:
                storage.move(dst / name, src / name)
            raise
    conn.execute("UPDATE class_uploads SET class_name=? WHERE school_id=? AND class_name=?", (new, school_id, old))


def status_of(cls: dict, counts: dict) -> str:
    """empty | in_progress | validated | special (Siblings). A validated class whose cards were all deleted or moved
    away is "empty" again (client 2026-10-28: "a class with no pupil nor photo shows 0, 0 and Empty")."""
    if cls["kind"] == "siblings":
        return "special"
    if cls["validated_at"] and (counts.get("filed") or not counts.get("foldered")):
        return "validated"
    return "in_progress" if counts.get("staged") else "empty"


# ── One file in ─────────────────────────────────────────────────────────────────────────────────

def _clean_name(filename: str) -> str:
    base = _BAD.sub("-", (filename or "").replace("\\", "/").rsplit("/", 1)[-1]).strip(" .-")
    return base[:120]


def _check(filename: str, data: bytes) -> str:
    name = _clean_name(filename)
    if not name or not name.lower().endswith(ALLOWED_EXT):
        raise UploadError("Not a photo (JPG, PNG or WebP only).")
    if not data:
        raise UploadError("Empty file.")
    if len(data) > config.UPLOAD_MAX_MB * 1024 * 1024:
        raise UploadError(f"File too large (max {config.UPLOAD_MAX_MB} MB).")
    try:
        with Image.open(io.BytesIO(data)) as im:
            im.verify()
    except Exception:
        raise UploadError("The file is not a readable picture.")
    return name


def _staging_key(school_id: str, class_name: str, upload_id: int, name: str) -> Key:
    return storage.key("photos", photo_service.STAGING_DIRNAME, school_id, photo_service.class_dirname(class_name),
                       f"{upload_id}_{name}")


# ── Thumbnails of the waiting photos (the explorer shows them before the class is validated) ────────────

STAGED_THUMB_PX = 360


def staged_thumb_url(school_id: str, upload_id: int) -> str:
    exp, sig = sign(f"staged:{school_id}/{upload_id}", 3600)
    return f"/api/media/staged-thumb/{school_id}/{upload_id}?exp={exp}&sig={sig}"


def _staged_thumb_key(school_id: str, upload_id: int) -> Key:
    return storage.key("thumbs", photo_service.STAGING_DIRNAME, school_id, f"{int(upload_id)}.webp")


def staged_thumb_path(school_id: str, upload_id: int, exp: int, sig: str):
    """The thumbnail of a waiting photo as a local file (or None: bad signature, photo gone)."""
    if not verify_signature(f"staged:{school_id}/{upload_id}", exp, sig):
        return None
    with get_db() as conn:
        row = conn.execute("SELECT class_name, filename FROM class_uploads WHERE id=? AND school_id=? AND state='staged'",
                           (upload_id, school_id)).fetchone()
    if not row:
        return None
    src, dst = _staging_key(school_id, row["class_name"], upload_id, row["filename"]), _staged_thumb_key(school_id, upload_id)
    try:
        if not media_service._fresh(dst, src):
            media_service._thumbnail(src, dst, STAGED_THUMB_PX, 72)
        return storage.local_path(dst)
    except Exception as exc:
        log.warning("Thumbnail of the waiting photo %s impossible: %s", upload_id, exc)
        return None


def _drop_staged_thumb(school_id: str, upload_id: int) -> None:
    try:
        storage.delete(_staged_thumb_key(school_id, upload_id))
    except Exception:
        pass                                              # a leftover thumbnail is harmless


def upload(school_id: str, class_id: int, filename: str, data: bytes, who: str, student: Optional[int] = None) -> dict:
    """Store one photo. Returns {"status": "uploaded"|"duplicate", ...}; raises UploadError for a refusal and
    LookupError for an unknown class. In a validated class or in Siblings the photo becomes a card at once — or, with
    `student`, joins that child's card (a second photo of a child already filed)."""
    cls = get_class(school_id, class_id)
    if cls["validated_at"] and cls["kind"] != "siblings" and status_of(cls, class_counts(school_id).get(cls["name"], {})) == "empty":
        # Emptied since it was validated: it starts over like a new class (photos wait for "Validate", grouped by child).
        with get_db() as conn:
            conn.execute("UPDATE school_classes SET validated_at=NULL WHERE id=?", (cls["id"],))
            conn.commit()
        cls["validated_at"] = None
    into = None
    if student is not None and cls["kind"] != "siblings" and cls["validated_at"]:
        into = _child_code(school_id, cls, student)
    name = _check(filename, data)
    digest = hashlib.sha256(data).hexdigest()
    with get_db() as conn:
        dup = conn.execute("SELECT id, filename, state, family_code FROM class_uploads "
                           "WHERE school_id=? AND class_name=? AND sha256=?", (school_id, cls["name"], digest)).fetchone()
        if dup and dup["state"] == "filed" and not photo_service.list_family_files(school_id, dup["family_code"] or ""):
            # Its card lost the photo (deleted to the trash): the same file may be loaded again.
            conn.execute("DELETE FROM class_uploads WHERE id=?", (dup["id"],))
            conn.commit()
            dup = None
        if dup:
            return {"status": "duplicate", "filename": name, "same_as": dup["filename"]}
        cur = conn.execute(
            "INSERT INTO class_uploads (school_id, class_name, filename, sha256, size, state, created_at, created_by) "
            "VALUES (?,?,?,?,?,'staged',?,?)", (school_id, cls["name"], name, digest, len(data), utcnow_iso(), who))
        conn.commit()
        upload_id = cur.lastrowid
    try:
        storage.write_bytes(_staging_key(school_id, cls["name"], upload_id, name), data)
    except Exception:
        with get_db() as conn:                       # a row without its file would count as a photo that is not there
            conn.execute("DELETE FROM class_uploads WHERE id=?", (upload_id,))
            conn.commit()
        log.exception("Upload %s/%s: storing %s failed", school_id, cls["name"], name)
        raise UploadError("The file could not be stored — try again.")
    result = {"status": "uploaded", "filename": name, "upload_id": upload_id, "state": "staged"}
    if cls["kind"] == "siblings" or cls["validated_at"]:
        card = _file_group(school_id, cls, [upload_id], into_code=into)
        result.update(state="filed", **card)
    return result


# ── From waiting photos to pupil cards ───────────────────────────────────────────────────────────

def _natural(name: str):
    return [int(p) if p.isdigit() else p.lower() for p in re.split(r"(\d+)", name)]


def _child_code(school_id: str, cls: dict, seq: int) -> str:
    """The family of `Student seq` of this class (a card that exists already)."""
    with get_db() as conn:
        row = conn.execute("SELECT family_code FROM child_folders WHERE school_id=? AND class_name=? AND seq=?",
                           (school_id, cls["name"], int(seq))).fetchone()
    if not row:
        raise UploadError(f"There is no Student {int(seq)} in this class.")
    return row["family_code"]


def _file_group(school_id: str, cls: dict, upload_ids: list[int], into_code: Optional[str] = None) -> dict:
    """Make ONE pupil card out of the waiting photos `upload_ids` (family + class + `{Class}/Student N` folder + the
    files), or add them to the card `into_code`. A photo whose file cannot be moved stays waiting."""
    with get_db() as conn:
        rows = [conn.execute("SELECT * FROM class_uploads WHERE id=? AND school_id=? AND state='staged'",
                             (i, school_id)).fetchone() for i in upload_ids]
    rows = [r for r in rows if r]
    if not rows:
        raise LookupError("Photo not found.")
    created = into_code is None
    code = into_code
    if created:
        with get_db() as conn:
            code = generate_unique_code(conn, school_service.code_prefix_for(school_id))
            conn.execute("INSERT INTO families (code, family_name, email, created_at, school_id) VALUES (?,?,?,?,?)",
                         (code, "", None, utcnow_iso(), school_id))
            conn.execute("INSERT INTO students (family_code, class_name) VALUES (?,?)", (code, cls["name"]))
            conn.commit()
    names, moved = [], 0
    try:
        folder = photo_service.child_dir(school_id, code, cls["name"])
        if folder is None:
            raise UploadError("The card folder could not be created.")
        for r in rows:
            target = photo_service.unique_name(school_id, code, folder, r["filename"])
            storage.move(_staging_key(school_id, cls["name"], r["id"], r["filename"]), target)   # keeps the arrival time
            moved += 1
            names.append(target.name)
            _drop_staged_thumb(school_id, r["id"])
            with get_db() as conn:
                conn.execute("UPDATE class_uploads SET state='filed', family_code=? WHERE id=?", (code, r["id"]))
                conn.commit()
    except Exception:
        if created and moved == 0:
            with get_db() as conn:                        # no card without a photo: take back the family just made
                conn.execute("DELETE FROM child_folders WHERE family_code=? AND school_id=?", (code, school_id))
                conn.execute("DELETE FROM students WHERE family_code=?", (code,))
                conn.execute("DELETE FROM families WHERE code=?", (code,))
                conn.commit()
        if moved == 0:
            raise
        log.exception("Card %s: %d of %d photos moved", code, moved, len(rows))      # keep what is there, report the rest
    with get_db() as conn:
        seq = conn.execute("SELECT seq FROM child_folders WHERE school_id=? AND family_code=? AND class_name=?",
                           (school_id, code, cls["name"])).fetchone()
    photo_service.invalidate_families_cache(school_id)
    n = seq["seq"] if seq else 0
    return {"code": code, "filename": names[0], "filenames": names, "seq": n or None,
            "label": card_label(cls["name"], n, cls["kind"] == "siblings")}


def card_label(class_name: str, seq: int, sibling_photo: bool = False) -> str:
    """"3A · Student 4" — a class and a number, never a name — or "Siblings · Photo 4" for the special folder."""
    return f"{class_name} · {'Photo' if sibling_photo else 'Student'} {seq}"


def list_waiting(school_id: str, class_id: int) -> list[dict]:
    cls = get_class(school_id, class_id)
    with get_db() as conn:
        rows = conn.execute("SELECT id, filename, size, created_at, child_no FROM class_uploads WHERE school_id=? AND "
                            "class_name=? AND state='staged'", (school_id, cls["name"])).fetchall()
    out = [{**dict(r), "thumb_url": staged_thumb_url(school_id, r["id"])} for r in rows]
    return sorted(out, key=lambda r: (_natural(r["filename"]), r["id"]))


def set_grouping(school_id: str, class_id: int, per_child: Optional[int] = None,
                 assign: Optional[dict[int, Optional[int]]] = None) -> list[dict]:
    """Group the waiting photos into children. `per_child=3`: every 3 photos in file order are one child (the camera
    shoots a child's photos in a row); `per_child=1` / 0 ungroups. `assign={upload id: child number | None}` sets
    individual photos. Photos that share a number become ONE card at validation."""
    cls = get_class(school_id, class_id)
    if cls["kind"] == "siblings" or cls["validated_at"]:
        raise UploadError("Only the photos waiting in a class that is not validated yet can be grouped.")
    waiting = list_waiting(school_id, class_id)
    ids = {w["id"] for w in waiting}
    with get_db() as conn:
        if per_child is not None:
            n = max(int(per_child), 1)
            for i, w in enumerate(waiting):
                conn.execute("UPDATE class_uploads SET child_no=? WHERE id=?", (i // n + 1 if n > 1 else None, w["id"]))
        for uid, no in (assign or {}).items():
            if int(uid) not in ids:
                raise UploadError("Unknown photo in the grouping.")
            if no is not None and not 1 <= int(no) <= 9999:
                raise UploadError("A child number is between 1 and 9999.")
            conn.execute("UPDATE class_uploads SET child_no=? WHERE id=?", (None if no is None else int(no), int(uid)))
        conn.commit()
    return list_waiting(school_id, class_id)


def validate_class(school_id: str, class_id: int, who: str) -> dict:
    """Turn the waiting photos of the class into pupil cards, one per child (photos sharing a number are one child),
    in file-name order. Safe to repeat: a photo that already became a card is not touched again, one that failed stays
    waiting and is reported."""
    cls = get_class(school_id, class_id)
    if cls["kind"] == "siblings":
        raise UploadError("The Siblings folder needs no validation: each photo is a card at once.")
    with named_lock(f"class-validate:{school_id}:{cls['id']}", timeout=30):
        waiting = list_waiting(school_id, class_id)
        if not waiting and not cls["validated_at"]:
            raise UploadError("There is no photo to validate in this class.")
        groups: dict[object, list[dict]] = {}
        for w in waiting:                                  # file order inside a group, a lone photo is its own child
            groups.setdefault(w["child_no"] if w["child_no"] is not None else ("solo", w["id"]), []).append(w)
        cards, failed = [], []
        for members in sorted(groups.values(), key=lambda g: (_natural(g[0]["filename"]), g[0]["id"])):
            try:
                cards.append(_file_group(school_id, cls, [m["id"] for m in members]))
            except Exception as exc:
                log.exception("Validating %s/%s: %s failed", school_id, cls["name"], members[0]["filename"])
                failed.extend({"filename": m["filename"], "detail": str(exc) or "error"} for m in members)
        with get_db() as conn:
            left = conn.execute("SELECT COUNT(*) AS n FROM class_uploads WHERE school_id=? AND class_name=? AND state='staged'",
                                (school_id, cls["name"])).fetchone()["n"]
            if not left:
                conn.execute("UPDATE school_classes SET validated_at=? WHERE id=? AND validated_at IS NULL",
                             (utcnow_iso(), cls["id"]))
                conn.commit()
    return {"class_name": cls["name"], "cards": len(cards), "photos": sum(len(c["filenames"]) for c in cards),
            "failed": failed, "validated": not left}


def remove_waiting(school_id: str, class_id: int, upload_id: int) -> str:
    """Take a photo out of the batch before the class is validated (wrong class, wrong file)."""
    cls = get_class(school_id, class_id)
    with get_db() as conn:
        row = conn.execute("SELECT * FROM class_uploads WHERE id=? AND school_id=? AND class_name=? AND state='staged'",
                           (upload_id, school_id, cls["name"])).fetchone()
        if not row:
            raise LookupError("Photo not found.")
        conn.execute("DELETE FROM class_uploads WHERE id=?", (upload_id,))
        conn.commit()
    try:
        storage.delete(_staging_key(school_id, cls["name"], upload_id, row["filename"]))
    except Exception as exc:
        log.warning("Staged file %s could not be deleted: %s", row["filename"], exc)
    _drop_staged_thumb(school_id, upload_id)
    return row["filename"]
