"""
family_service.py — siblings: two family codes that turn out to be ONE family.

Nobody can tell from a photo (and we may not ask for a name) that the child of 2A/Student 3 and the one of
3B/Student 7 are brother and sister. Someone who knows says it:
  * the operator, before the cards are printed, from the list the school gives (Cards tab, "Join as siblings");
  * the parents, afterwards: they received two cards, they open one and type the code of the other one.
Both end here. `merge(keep, other)` makes `other` an alias of `keep`:
  * every `Clase/Student N` folder of `other` now belongs to `keep` (the folders do not move on disk: the
    client's layout stays school/class/student), so the gallery and the 10x15 sheet show all the children;
  * its classes, its orders (and their downloads) and its consent go to `keep`;
  * `families.merged_into` remembers it, so the card already printed with `other` still opens the family.
A file name must stay unique in a family (photos are found by code + name): a clash is renamed on the `other`
side, in its order lines and in its meta.json too, so a paid download keeps pointing at the right picture.

Client brief 2026-10-21 (sheet 6b): a merge is CONFIRMED by the operator, kept in `family_merges` (who, when, which
cards) and can be UNDONE: `unmerge` gives the folders, classes and orders back to the card that was absorbed. The kept
code is the first card's. A merge cannot be undone when it cannot be undone exactly: the kept family was merged again
since (undo that one first), it has taken orders since the merge, or an old-layout folder was moved on disk.
The "Siblings" folder is not a class of the family: a sibling-photo card joined to a family adds no class to it.
"""
import json
import logging
from typing import Optional

from core import storage
from core.db import TABLE_OPTIONS, get_db, named_lock
from core.storage import Key
from core.timeutil import utcnow_iso
from services import photo_service

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

_MAX_HOPS = 5


class MergeError(ValueError):
    pass


def init_tables() -> None:
    with get_db() as conn:
        conn.execute(f"""
        CREATE TABLE IF NOT EXISTS family_merges (
            id         INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            school_id  VARCHAR(64) NOT NULL,
            kept       VARCHAR(32) NOT NULL,
            other      VARCHAR(32) NOT NULL,
            created_at VARCHAR(40) NOT NULL,
            created_by VARCHAR(40),
            undone_at  VARCHAR(40),
            undone_by  VARCHAR(40),
            data       MEDIUMTEXT NOT NULL,
            KEY idx_merges_school (school_id, undone_at),
            KEY idx_merges_other (other)
        ) {TABLE_OPTIONS}""")
        conn.commit()


def canonical(conn, code: str) -> Optional[str]:
    """The code a (possibly merged) code stands for now, or None if the family does not exist."""
    seen = 0
    while seen <= _MAX_HOPS:
        row = conn.execute("SELECT code, merged_into FROM families WHERE code=?", (code,)).fetchone()
        if not row:
            return None
        if not row["merged_into"]:
            return row["code"]
        code = row["merged_into"]
        seen += 1
    logger.error("Family merge chain too long from %s", code)
    return code


def canonical_code(code: str) -> Optional[str]:
    with get_db() as conn:
        return canonical(conn, code)


def _rename_clashes(school_id: str, keep: str, other: str) -> dict[str, str]:
    """Rename (in storage, in `other`'s folders) every file whose name `keep` already has. Returns {old: new}."""
    taken = {p.name for _l, d in photo_service.family_dirs(school_id, keep) for p in photo_service._safe_iter(d)}
    renamed: dict[str, str] = {}
    for _label, folder in photo_service.family_dirs(school_id, other):
        for f in photo_service._safe_iter(folder):
            if f.name.startswith(".") or f.name not in taken:
                continue
            stem, suffix, n = f.stem, f.suffix, 1
            new = f"{stem}_{n}{suffix}"
            while new in taken or storage.exists(folder / new):
                n += 1
                new = f"{stem}_{n}{suffix}"
            photo_service.drop_derivatives(f.key)
            storage.move(f.key, folder / new)
            taken.add(new)
            renamed[f.name] = new
            _rename_in_meta(folder, f.name, new)
    return renamed


def _rename_in_meta(folder: Key, old: str, new: str) -> None:
    meta = folder / "meta.json"
    if not storage.exists(meta):
        return
    try:
        data = json.loads(storage.read_text(meta))
        names = data.get("photo_names", {})
        if old in names:
            names[new] = names.pop(old)
            storage.write_text(meta, json.dumps(data, ensure_ascii=False, indent=2))
    except Exception as exc:
        logger.warning("meta.json of %s not updated after a rename: %s", folder, exc)


def _move_legacy_folders(school_id: str, keep: str, other: str) -> bool:
    """Folders of the older layouts are named after the code: their files move under `keep`'s folder.
    Returns whether any did (an undo cannot put them back)."""
    moved = False
    for label, folder in photo_service.family_dirs(school_id, other):
        if "/" in label:                         # Clase/Student N: re-pointed in the database, not moved
            continue
        moved = True
        parent = folder.parent
        target = photo_service.resolve_qr_folder(parent, keep) or (parent / keep)
        storage.mkdir(target)
        for f in storage.walk(folder):
            dest = Key(target, *f.key.parts[len(folder.parts):])
            if storage.exists(dest):
                continue                         # cannot happen after _rename_clashes, never overwrite anyway
            storage.move(f.key, dest)
        if not storage.walk(folder):
            storage.delete_tree(folder)          # the empty folder (on disk; a bucket has none)
    return moved


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


def merge(school_id: str, keep: str, other: str, by: str = "") -> dict:
    """Make `other` part of `keep`'s family. Raises MergeError (nothing changed) for anything inconsistent."""
    with named_lock(f"family-merge:{school_id}", timeout=10):
        with get_db() as conn:
            k = canonical(conn, keep)
            o = canonical(conn, other)
            if not k or not o:
                raise MergeError("Unknown family code.")
            rows = conn.execute("SELECT code, school_id FROM families WHERE code IN (?,?)", (k, o)).fetchall()
            if len(rows) != (1 if k == o else 2) or any(r["school_id"] != school_id for r in rows):
                raise MergeError("Both codes must belong to this school.")
            if k == o:
                raise MergeError("These codes are already the same family.")

        renamed = _rename_clashes(school_id, k, o)
        legacy_moved = _move_legacy_folders(school_id, k, o)

        with get_db() as conn:
            sib = _sibling_classes(conn, school_id)

            def _state(code: str):
                row = conn.execute("SELECT card_state FROM families WHERE code=?", (code,)).fetchone()
                return row["card_state"] if row else None
            undo: dict = {
                "folder_ids": [r["id"] for r in conn.execute(
                    "SELECT id FROM child_folders WHERE family_code=? AND school_id=?", (o, school_id))],
                "other_classes": [r["class_name"] for r in conn.execute(
                    "SELECT class_name FROM students WHERE family_code=? ORDER BY id", (o,))],
                "kept_classes_before": [r["class_name"] for r in conn.execute(
                    "SELECT class_name FROM students WHERE family_code=? ORDER BY id", (k,))],
                "aliases": [r["code"] for r in conn.execute("SELECT code FROM families WHERE merged_into=?", (o,))],
                "renamed": renamed, "legacy_moved": legacy_moved,
                "card_state": {k: _state(k), o: _state(o)},
            }
            conn.execute("UPDATE child_folders SET family_code=? WHERE family_code=? AND school_id=?", (k, o, school_id))
            mine = {r["class_name"] for r in conn.execute("SELECT class_name FROM students WHERE family_code=?", (k,))}
            for r in conn.execute("SELECT class_name FROM students WHERE family_code=? ORDER BY id", (o,)).fetchall():
                # A sibling PHOTO is not a class of the family: only real classes join it.
                if r["class_name"] not in mine and r["class_name"] not in sib:
                    conn.execute("INSERT INTO students (family_code, class_name) VALUES (?,?)", (k, r["class_name"]))
                    mine.add(r["class_name"])
            conn.execute("DELETE FROM students WHERE family_code=?", (o,))
            if mine - sib:                                   # the kept card was a sibling photo: now it has classes
                for name in mine & sib:
                    conn.execute("DELETE FROM students WHERE family_code=? AND class_name=?", (k, name))
            src = conn.execute("SELECT * FROM families WHERE code=?", (o,)).fetchone()
            conn.execute("UPDATE families SET email=COALESCE(email, ?), consent_at=COALESCE(consent_at, ?), "
                         "consent_ip=COALESCE(consent_ip, ?) WHERE code=?",
                         (src["email"], src["consent_at"], src["consent_ip"], k))
            conn.execute("UPDATE families SET merged_into=? WHERE code=?", (k, o))
            # Aliases of `other` follow it (one hop instead of a chain).
            conn.execute("UPDATE families SET merged_into=? WHERE merged_into=?", (k, o))
            orders = conn.execute("SELECT id, items_json FROM orders WHERE family_code=?", (o,)).fetchall()
            undo["order_ids"] = [row["id"] for row in orders]
            for row in orders:
                items = json.loads(row["items_json"])
                if renamed:
                    for it in items:
                        if it.get("photo_filename") in renamed:
                            it["photo_filename"] = renamed[it["photo_filename"]]
                conn.execute("UPDATE orders SET family_code=?, items_json=? WHERE id=?",
                             (k, json.dumps(items, ensure_ascii=False), row["id"]))
            cur = conn.execute("INSERT INTO family_merges (school_id, kept, other, created_at, created_by, data) "
                               "VALUES (?,?,?,?,?,?)", (school_id, k, o, utcnow_iso(), by, json.dumps(undo)))
            merge_id = cur.lastrowid
            conn.commit()
    photo_service.invalidate_families_cache(school_id)
    logger.info("Colegio %s: familia %s unida a %s (%d archivo(s) renombrado(s), %d pedido(s))",
                school_id, o, k, len(renamed), len(orders))
    return {"code": k, "merged": o, "renamed": renamed, "orders": len(orders), "merge_id": merge_id}


def list_merges(school_id: str, active_only: bool = True) -> list[dict]:
    with get_db() as conn:
        rows = conn.execute("SELECT * FROM family_merges WHERE school_id=?" + (" AND undone_at IS NULL" if active_only else "")
                            + " ORDER BY id DESC", (school_id,)).fetchall()
    return [{**{k: r[k] for k in ("id", "kept", "other", "created_at", "created_by", "undone_at", "undone_by")},
             "data": json.loads(r["data"])} for r in rows]


def unmerge(school_id: str, merge_id: int, by: str = "") -> dict:
    """Give a merged card back its own code, folders, classes and orders. Raises MergeError (nothing changed) when
    it cannot be done exactly — see the module docstring."""
    with named_lock(f"family-merge:{school_id}", timeout=10):
        with get_db() as conn:
            m = conn.execute("SELECT * FROM family_merges WHERE id=? AND school_id=?", (merge_id, school_id)).fetchone()
            if not m:
                raise MergeError("Merge not found.")
            if m["undone_at"]:
                raise MergeError("This merge was already undone.")
            data = json.loads(m["data"])
            kept, other = m["kept"], m["other"]
            fam_k = conn.execute("SELECT merged_into FROM families WHERE code=?", (kept,)).fetchone()
            fam_o = conn.execute("SELECT merged_into FROM families WHERE code=?", (other,)).fetchone()
            if not fam_k or not fam_o:
                raise MergeError("One of the cards no longer exists.")
            if fam_k["merged_into"] or fam_o["merged_into"] != kept:
                raise MergeError("The family was merged again since: undo the later merge first.")
            if data.get("legacy_moved"):
                raise MergeError("Photos of an old layout were moved by this merge: it cannot be undone.")
            # Orders that came from another card merged into the same family later are not "the family ordering".
            later = [json.loads(r["data"]).get("order_ids", []) for r in conn.execute(
                "SELECT data FROM family_merges WHERE school_id=? AND kept=? AND undone_at IS NULL AND id>?",
                (school_id, kept, merge_id))]
            moved_later = {oid for ids in later for oid in ids}
            since = [r["id"] for r in conn.execute("SELECT id FROM orders WHERE family_code=? AND created_at > ?",
                                                   (kept, m["created_at"])) if r["id"] not in moved_later]
            if since:
                raise MergeError("The family has ordered since the merge: it cannot be undone any more.")
            for fid in data["folder_ids"]:
                conn.execute("UPDATE child_folders SET family_code=? WHERE id=? AND school_id=?", (other, fid, school_id))
            # classes: the absorbed card gets its own back; the kept one loses what only this merge had added
            # (a class it still has a folder in, or had before, stays)
            conn.execute("DELETE FROM students WHERE family_code=?", (other,))
            for cls in data["other_classes"]:
                conn.execute("INSERT INTO students (family_code, class_name) VALUES (?,?)", (other, cls))
            still = {r["class_name"] for r in conn.execute(
                "SELECT class_name FROM child_folders WHERE family_code=? AND school_id=?", (kept, school_id))}
            for cls in data["other_classes"]:
                if cls not in data["kept_classes_before"] and cls not in still:
                    conn.execute("DELETE FROM students WHERE family_code=? AND class_name=?", (kept, cls))
            if not conn.execute("SELECT 1 FROM students WHERE family_code=?", (kept,)).fetchone():
                for cls in data["kept_classes_before"]:        # it had only the sibling-photo class
                    conn.execute("INSERT INTO students (family_code, class_name) VALUES (?,?)", (kept, cls))
            conn.execute("UPDATE families SET merged_into=NULL WHERE code=?", (other,))
            for alias in data["aliases"]:
                conn.execute("UPDATE families SET merged_into=? WHERE code=?", (other, alias))
            for oid in data["order_ids"]:
                conn.execute("UPDATE orders SET family_code=? WHERE id=?", (other, oid))
            for code, state in data["card_state"].items():
                conn.execute("UPDATE families SET card_state=? WHERE code=?", (state, code))
            conn.execute("UPDATE family_merges SET undone_at=?, undone_by=? WHERE id=?", (utcnow_iso(), by, merge_id))
            conn.commit()
    photo_service.invalidate_families_cache(school_id)
    logger.info("Colegio %s: fusión %s deshecha (%s separada de %s)", school_id, merge_id, other, kept)
    return {"kept": kept, "restored": other, "merge_id": merge_id}
