"""Persistent saved builds with version lineage.

Drafts live in the Flask session (build.py). On save, we snapshot
the active draft into a `build` row + `build_item` rows.

**Lineage model:** every build belongs to a *lineage* — a chain of
versions descended from a single "first save." Updating a saved
build mints a NEW build row with `parent_build_id` pointing back +
`root_build_id` shared across the whole lineage + a denormalized
`is_latest=1` flag (the previous latest's flag flips to 0).

Why per-version rows (not edit-in-place):
  - Forum post share URLs stay stable forever — the URL points to a
    specific version snapshot.
  - "What did this build look like 3 weeks ago?" answerable via the
    lineage history.
  - Diffs between versions are trivially computable.
  - Restock alerts target the lineage (the latest version's items)
    rather than a frozen point in time.

**Idempotency:** if a save would mint a version identical (same
{parts_id: qty}) to the current latest of its target lineage, we
return the existing URL instead of writing a duplicate row.

See:
  - site-ng/docs/build-feature-design.md (Identity model, data model)
  - memory: feature-site-share-builds (locked design 2026-05-25)
"""

from __future__ import annotations

import hashlib
import secrets
import string
from typing import Optional

from flask import session

from .db import get_db
from .queries import parts_by_ids


# Short-code alphabet: base62 minus ambiguous chars (0/O/o/1/l/I).
_CODE_ALPHABET = "".join(
    c for c in (string.ascii_letters + string.digits)
    if c not in "0Oo1lI")
_CODE_LEN = 8


def _generate_unique_code() -> str:
    """Random 8-char code, uniqueness-checked against the build table."""
    cur = get_db().cursor()
    for _ in range(8):
        code = "".join(secrets.choice(_CODE_ALPHABET)
                       for _ in range(_CODE_LEN))
        cur.execute("SELECT 1 FROM build WHERE code=%s", (code,))
        if not cur.fetchone():
            return code
    raise RuntimeError("Could not allocate unique build code after 8 tries")


# --------------------------------------------------------------------------- #
# Content fingerprinting (for idempotency checks)
# --------------------------------------------------------------------------- #
def _fingerprint(bmap: dict) -> str:
    """Hash of the sorted (parts_id, qty) tuples — used to detect
    "draft is identical to existing build" before writing a new row.
    Sorting makes it order-independent; SHA-256 keeps it cheap +
    collision-safe at our scale."""
    items = sorted(((int(k), int(v)) for k, v in bmap.items()),
                   key=lambda t: t[0])
    canonical = ",".join(f"{pid}x{qty}" for pid, qty in items)
    return hashlib.sha256(canonical.encode()).hexdigest()


def _items_to_bmap(items: list) -> dict:
    """Inverse of _fingerprint's input — turn a list of build_item
    rows back into a {parts_id_str: qty} map for comparison."""
    out = {}
    for it in items:
        if not it.get("parts_id"):
            continue
        key = str(it["parts_id"])
        out[key] = out.get(key, 0) + int(it["qty"] or 1)
    return out


# --------------------------------------------------------------------------- #
# Read paths
# --------------------------------------------------------------------------- #
def get_by_code(code: str) -> Optional[dict]:
    """Fetch a build header row by share code."""
    if not code:
        return None
    cur = get_db().cursor()
    cur.execute(
        "SELECT id, code, owner_user_id, parent_build_id, root_build_id, "
        "       is_latest, title, notes, votes, status, created, updated "
        "FROM build WHERE code=%s",
        (code,))
    return cur.fetchone()


def get_by_id(build_id: int) -> Optional[dict]:
    if not build_id:
        return None
    cur = get_db().cursor()
    cur.execute(
        "SELECT id, code, owner_user_id, parent_build_id, root_build_id, "
        "       is_latest, title, notes, votes, status, created, updated "
        "FROM build WHERE id=%s",
        (int(build_id),))
    return cur.fetchone()


def get_items(build_id: int) -> list:
    """All build_item rows for a build, sorted by position. img URLs
    are sanitized via _safe_img_url (security finding M3)."""
    from .queries import _sanitize_imgs
    cur = get_db().cursor()
    cur.execute(
        "SELECT id, parts_id, qty, type, company, description, "
        "       url, img, price_at_add, position, added "
        "FROM build_item WHERE build_id=%s ORDER BY position, id",
        (int(build_id),))
    return _sanitize_imgs(list(cur.fetchall()))


def list_for_user(user_id: int) -> list:
    """One row per LINEAGE (latest version) owned by this user, with a
    version count + totals. Used by /my-builds.

    Returns: list of dicts with keys: id, code, root_build_id, title,
    created, updated, line_count, total_qty, total_at_save, n_versions."""
    if not user_id:
        return []
    cur = get_db().cursor()
    cur.execute(
        "SELECT b.id, b.code, b.root_build_id, b.title, "
        "       b.created, b.updated, "
        "       COUNT(DISTINCT bi.id) AS line_count, "
        "       SUM(bi.qty) AS total_qty, "
        "       SUM(bi.price_at_add * bi.qty) AS total_at_save, "
        "       (SELECT COUNT(*) FROM build "
        "        WHERE root_build_id=b.root_build_id) AS n_versions "
        "FROM build b "
        "LEFT JOIN build_item bi ON bi.build_id = b.id "
        "WHERE b.owner_user_id=%s AND b.is_latest=1 "
        "GROUP BY b.id "
        "ORDER BY b.updated DESC",
        (int(user_id),))
    return list(cur.fetchall())


def get_versions(root_build_id: int) -> list:
    """All versions of a lineage, newest first. Used to expand a
    /my-builds row into its history."""
    if not root_build_id:
        return []
    cur = get_db().cursor()
    cur.execute(
        "SELECT b.id, b.code, b.parent_build_id, b.is_latest, "
        "       b.title, b.created, b.updated, "
        "       COUNT(DISTINCT bi.id) AS line_count, "
        "       SUM(bi.qty) AS total_qty, "
        "       SUM(bi.price_at_add * bi.qty) AS total_at_save "
        "FROM build b "
        "LEFT JOIN build_item bi ON bi.build_id = b.id "
        "WHERE b.root_build_id=%s "
        "GROUP BY b.id "
        "ORDER BY b.created DESC",
        (int(root_build_id),))
    return list(cur.fetchall())


def diff_against_parent(build_id: int) -> Optional[dict]:
    """Compute the item diff between this build and its parent.
    Returns None if this is a root (no parent). Otherwise:
      {added: [{parts_id, qty, description}, ...],
       removed: [{parts_id, qty, description}, ...],
       qty_changed: [{parts_id, old_qty, new_qty, description}, ...]}
    """
    head = get_by_id(build_id)
    if not head or not head.get("parent_build_id"):
        return None
    cur_items = get_items(build_id)
    parent_items = get_items(head["parent_build_id"])
    cur_map = {int(it["parts_id"]): it
               for it in cur_items if it.get("parts_id")}
    parent_map = {int(it["parts_id"]): it
                  for it in parent_items if it.get("parts_id")}
    added, removed, changed = [], [], []
    for pid, it in cur_map.items():
        if pid not in parent_map:
            added.append({"parts_id": pid, "qty": int(it["qty"]),
                          "description": it["description"]})
        elif int(it["qty"]) != int(parent_map[pid]["qty"]):
            changed.append({"parts_id": pid,
                            "old_qty": int(parent_map[pid]["qty"]),
                            "new_qty": int(it["qty"]),
                            "description": it["description"]})
    for pid, it in parent_map.items():
        if pid not in cur_map:
            removed.append({"parts_id": pid, "qty": int(it["qty"]),
                            "description": it["description"]})
    return {"added": added, "removed": removed, "qty_changed": changed}


# --------------------------------------------------------------------------- #
# Save paths
# --------------------------------------------------------------------------- #
def _insert_version(*, owner_user_id, parent_build_id, root_build_id,
                    title, bmap, parts_map):
    """Internal: write a single build row + its build_items.
    Returns (build_id, code). parent_build_id / root_build_id may be
    None when starting a new lineage (caller will fix root_build_id
    in a second UPDATE since it self-references the row's own id)."""
    code = _generate_unique_code()
    cur = get_db().cursor()
    cur.execute(
        "INSERT INTO build "
        "  (code, owner_user_id, parent_build_id, root_build_id, "
        "   is_latest, title, status, created, updated) "
        "VALUES (%s, %s, %s, %s, 1, %s, 'public', NOW(), NOW())",
        (code, owner_user_id, parent_build_id, root_build_id,
         title))
    build_id = cur.lastrowid
    # If starting a new lineage, root_build_id self-references.
    if root_build_id is None:
        cur.execute(
            "UPDATE build SET root_build_id=%s WHERE id=%s",
            (build_id, build_id))
    pos = 0
    for pid_str, qty in bmap.items():
        pid = int(pid_str)
        p = parts_map.get(pid)
        if not p:
            continue
        cur.execute(
            "INSERT INTO build_item "
            "  (build_id, parts_id, qty, type, company, description, "
            "   url, img, price_at_add, position, added) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())",
            (build_id, pid, int(qty), p["type"], p["company"],
             (p["description"] or "")[:255],
             (p["url"] or "")[:500],
             (p["img"] or "")[:500] if p.get("img") else None,
             p.get("price"), pos))
        pos += 1
    return build_id, code


def save_new_lineage(*, title: Optional[str] = None,
                     owner_user_id: Optional[int] = None
                     ) -> Optional[dict]:
    """Promote the active draft into a NEW lineage. Idempotency
    check: if the owner already has an owned build whose latest
    version has the same items, return that lineage's URL instead of
    minting a duplicate. (Anonymous saves don't dedup — we have no
    way to attribute them to a single user.)

    Returns dict {code, build_id, was_dup}. None on empty draft."""
    from .build import _ensure_session
    _ensure_session()
    active_slot = session["active"]
    active = session["drafts"][active_slot]
    bmap = active.get("items") or {}
    if not bmap:
        return None

    ids = [int(k) for k in bmap.keys()]
    parts_map = parts_by_ids(ids)
    if not parts_map:
        # Every item was purged from the parts table — nothing to save.
        return None

    save_title = (title or active.get("name") or "").strip()[:120] or None

    # Idempotency: only for owned saves (anonymous = can't attribute).
    if owner_user_id:
        existing = _find_duplicate_for_owner(owner_user_id, bmap)
        if existing:
            return {"code": existing["code"], "build_id": existing["id"],
                    "was_dup": True}

    build_id, code = _insert_version(
        owner_user_id=owner_user_id,
        parent_build_id=None, root_build_id=None,
        title=save_title, bmap=bmap, parts_map=parts_map)
    get_db().commit()
    # Stamp the draft so subsequent edits can target Update.
    _associate_draft_with_build(active_slot, build_id, code)
    # For anonymous saves, ALSO append the code to a persistent session
    # list. This is the proof-of-ownership the claim flow checks: only
    # the browser that did the save can later claim the build (security
    # finding H3). The draft-side stamp is the primary proof, but the
    # draft can be deleted while the user still legitimately wants to
    # claim — this list survives draft deletion.
    # Capped at 50 entries to keep the cookie small; older entries
    # rotate out FIFO. Sliding-window claim ability is fine — a user
    # claiming a 6-month-old anonymous build is a rare path, and the
    # cookie's own TTL (60 days) is a tighter ceiling anyway.
    if owner_user_id is None:
        anon_saves = list(session.get("anon_saves") or [])
        if code not in anon_saves:
            anon_saves.append(code)
            session["anon_saves"] = anon_saves[-50:]
            session.modified = True
    return {"code": code, "build_id": build_id, "was_dup": False}


def save_update_lineage(parent_build: dict, *,
                        title: Optional[str] = None
                        ) -> Optional[dict]:
    """Mint a new version of an existing lineage. The new version's
    parent_build_id = the lineage's current latest (passed in), and
    root_build_id is inherited.

    The caller must verify ownership before calling — we don't
    re-check here (this is the bare DB op).

    Returns dict {code, build_id, was_dup}. was_dup=True when the
    draft's items already match the lineage's current latest (no row
    written, existing code returned)."""
    from .build import _ensure_session
    _ensure_session()
    active_slot = session["active"]
    active = session["drafts"][active_slot]
    bmap = active.get("items") or {}
    if not bmap:
        return None

    # Idempotency: if draft items === parent_build's items, no-op.
    parent_items = get_items(parent_build["id"])
    parent_bmap = _items_to_bmap(parent_items)
    if _fingerprint(bmap) == _fingerprint(parent_bmap):
        return {"code": parent_build["code"], "build_id": parent_build["id"],
                "was_dup": True}

    ids = [int(k) for k in bmap.keys()]
    parts_map = parts_by_ids(ids)
    if not parts_map:
        return None

    save_title = ((title or parent_build.get("title") or "")
                  .strip()[:120] or None)
    root_id = parent_build.get("root_build_id") or parent_build["id"]

    # Flip the parent's is_latest=0 BEFORE inserting the new version
    # so the (owner, is_latest) index never momentarily shows two
    # latest rows for the same lineage.
    cur = get_db().cursor()
    cur.execute(
        "UPDATE build SET is_latest=0, updated=NOW() WHERE id=%s",
        (parent_build["id"],))

    build_id, code = _insert_version(
        owner_user_id=parent_build.get("owner_user_id"),
        parent_build_id=parent_build["id"], root_build_id=root_id,
        title=save_title, bmap=bmap, parts_map=parts_map)
    get_db().commit()
    _associate_draft_with_build(active_slot, build_id, code)
    return {"code": code, "build_id": build_id, "was_dup": False}


def _find_duplicate_for_owner(owner_user_id: int,
                               bmap: dict) -> Optional[dict]:
    """Among the user's owned latest-version builds, find one whose
    items match `bmap` (same parts + same quantities). Returns the
    build header dict or None."""
    fp = _fingerprint(bmap)
    cur = get_db().cursor()
    cur.execute(
        "SELECT id, code FROM build "
        "WHERE owner_user_id=%s AND is_latest=1", (int(owner_user_id),))
    for row in cur.fetchall():
        items = get_items(row["id"])
        if _fingerprint(_items_to_bmap(items)) == fp:
            return row
    return None


def _associate_draft_with_build(slot: str, build_id: int,
                                code: str) -> None:
    """Set saved_code + saved_build_id on the draft, so subsequent
    edits know what lineage they're working against."""
    session["drafts"][slot]["saved_code"] = code
    session["drafts"][slot]["saved_build_id"] = int(build_id)
    session.modified = True


def clear_draft_association(slot: str) -> None:
    """Remove the saved_code linkage on a draft — used when the user
    explicitly starts fresh / clears."""
    d = session.get("drafts", {}).get(slot)
    if d:
        d.pop("saved_code", None)
        d.pop("saved_build_id", None)
        session.modified = True


# --------------------------------------------------------------------------- #
# Mutations on existing builds
# --------------------------------------------------------------------------- #
def delete_lineage(root_build_id: int, owner_user_id: int) -> int:
    """Delete every version in a lineage. Owner-only — the WHERE
    clause enforces this so a user can't delete another user's
    lineage. Returns the number of versions deleted (0 if not owned)."""
    if not root_build_id or not owner_user_id:
        return 0
    cur = get_db().cursor()
    cur.execute(
        "DELETE FROM build "
        "WHERE root_build_id=%s AND owner_user_id=%s",
        (int(root_build_id), int(owner_user_id)))
    get_db().commit()
    return cur.rowcount


def claim(build_id: int, owner_user_id: int) -> bool:
    """Associate every version of a lineage with a user (the user is
    claiming an anonymous build). No-op if any version is already
    owned — won't let a user steal another user's lineage."""
    if not build_id or not owner_user_id:
        return False
    head = get_by_id(build_id)
    if not head:
        return False
    root = head.get("root_build_id") or head["id"]
    cur = get_db().cursor()
    # Refuse if ANY version of the lineage has an owner already.
    cur.execute(
        "SELECT COUNT(*) AS n FROM build "
        "WHERE root_build_id=%s AND owner_user_id IS NOT NULL",
        (root,))
    if int(cur.fetchone()["n"]) > 0:
        return False
    cur.execute(
        "UPDATE build SET owner_user_id=%s, updated=NOW() "
        "WHERE root_build_id=%s",
        (int(owner_user_id), root))
    get_db().commit()
    return cur.rowcount > 0


def browser_has_claim_proof(code: str) -> bool:
    """Return True if THIS browser's session can prove it saved the
    anonymous build identified by `code`. Two acceptance paths:

      1. session['anon_saves'] contains the code — the persistent
         list updated by save_new_lineage on every anonymous save.
         Survives draft deletion.
      2. Any session draft has its saved_code field set to this code
         — the per-draft stamp that drives the chip-dropdown 💾 badge
         and the Update/Save-as-new button branching.

    Either is sufficient: both are written to the same signed session
    cookie at save time, so an attacker would need the SECRET_KEY to
    forge either one. The dual check just covers both states the
    cookie can naturally end up in (draft present vs. draft deleted)
    without making the user lose claim ability when they tidy up.

    Used by views/saves.py claim_build and public_view to gate the
    Claim button + endpoint. See security review H3."""
    if not code:
        return False
    anon_saves = session.get("anon_saves") or []
    if code in anon_saves:
        return True
    drafts = session.get("drafts") or {}
    for d in drafts.values():
        if d.get("saved_code") == code:
            return True
    return False


def find_slot_by_saved_code(code: str) -> Optional[str]:
    """Return the slot key of an existing draft already linked to this
    saved-build code, or None. Used by load_into_draft to avoid
    duplicate drafts of the same lineage — if you click 'Continue
    editing' on a build you're already editing, we just switch to
    that existing draft."""
    if not code:
        return None
    drafts = session.get("drafts") or {}
    for s, d in drafts.items():
        if d.get("saved_code") == code:
            return s
    return None


def _pick_or_make_slot() -> Optional[str]:
    """Slot to load a build into: the first EMPTY existing slot, else a NEW
    slot if we're under MAX_DRAFTS, else None (caller shows the slot-picker).

    Bugfix 2026-06-06: previously the load paths only reused an empty EXISTING
    slot and returned None otherwise, so a single non-empty draft made the
    app claim "all slots in use" and show the replace-picker despite 4 free
    slots below the cap. Now it allocates a fresh slot first, matching
    new_draft()'s next_n allocation."""
    from .build import MAX_DRAFTS
    for s, d in session["drafts"].items():
        if not d.get("items"):
            return s
    if len(session["drafts"]) < MAX_DRAFTS:
        n = session.get("next_n", len(session["drafts"]) + 1)
        session["next_n"] = n + 1
        return str(n)
    return None


def load_into_draft(code: str, *, slot: Optional[str] = None,
                    preserve_link: bool = True) -> Optional[dict]:
    """Load a saved build's items into a draft slot.

    Two modes (selected by preserve_link):
      - preserve_link=True (default) — "Continue editing": stamp
        saved_code on the draft so Save = new version of THIS lineage.
        Only sensible when the loader is the lineage owner.
      - preserve_link=False — "Use as a starting point" / true fork:
        do NOT stamp saved_code, so Save creates a new lineage owned
        by the loader. Right behavior for non-owners and for owners
        who explicitly want to start a derivative.

    Slot selection (in priority order):
      1. Explicit `slot` arg if provided AND that slot exists.
      2. If preserve_link AND a draft already has this saved_code,
         switch to it instead of creating a duplicate.
      3. First empty slot.
      4. Active slot (only if no empty slot is free — destructive
         fallback when the user is at the cap).

    Returns the build_summary() shape so callers can render immediately."""
    from .build import _ensure_session, build_summary
    head = get_by_code(code)
    if not head:
        return None
    items = get_items(head["id"])
    _ensure_session()
    if slot and slot in session["drafts"]:
        # Explicit slot override — caller is the slot-picker modal
        # confirming user choice. Whatever is in this slot will be
        # replaced. Caller is responsible for the confirmation UX.
        target = slot
    elif preserve_link:
        # If a draft already links this lineage, REUSE that slot (so
        # we don't allocate a duplicate) — but fall through to the
        # item-reload below rather than just switching to whatever is
        # currently in the slot. Clicking Edit means "give me a fresh
        # working copy of this build's current saved content," not
        # "resume whatever I last left here" (Mike 2026-05-27: empty
        # a linked draft, click Edit again → should restore the saved
        # items, not hand back the emptied draft). The chip dropdown's
        # draft-switch is the "resume in-progress" path; Edit reloads.
        existing = find_slot_by_saved_code(code)
        if existing:
            target = existing
        else:
            # Find an empty slot. If none exists, return None and let
            # the caller show a slot-picker (drafts/saved model
            # reshape 2026-05-27: no silent destructive overwrite of
            # the active draft).
            target = _pick_or_make_slot()
            if target is None:
                return None
    else:
        # Non-preserve-link path (fork). Same rules — empty slot or
        # nothing; caller handles the picker if needed.
        target = _pick_or_make_slot()
        if target is None:
            return None
    bmap = _items_to_bmap(items)
    draft = {
        "name": head.get("title") or f"Build #{target}",
        "items": bmap,
    }
    if preserve_link:
        draft["saved_code"] = code
        draft["saved_build_id"] = int(head["id"])
    session["drafts"][target] = draft
    session["active"] = target
    session.modified = True
    return build_summary()


def list_recent_saved_for_user(user_id: int, limit: int = 5) -> list:
    """Latest-version row per lineage for a user, capped at `limit`,
    sorted by most-recently-updated. Used by the build-chip dropdown's
    "Saved" mini-section so the user sees recent saves at a glance
    without clicking through to /my-builds.

    Cheaper than list_for_user (no version-count subquery, no item
    aggregates) because the dropdown only needs title + code + updated."""
    if not user_id:
        return []
    cur = get_db().cursor()
    cur.execute(
        "SELECT id, code, title, updated "
        "FROM build WHERE owner_user_id=%s AND is_latest=1 "
        "ORDER BY updated DESC LIMIT %s",
        (int(user_id), int(limit)))
    return list(cur.fetchall())


def count_saved_for_user(user_id: int) -> int:
    """Total number of saved-build LINEAGES owned by a user (one per
    lineage, not per version). Drives the 'All my saved builds (N) →'
    link label in the chip dropdown."""
    if not user_id:
        return 0
    cur = get_db().cursor()
    cur.execute(
        "SELECT COUNT(*) AS n FROM build "
        "WHERE owner_user_id=%s AND is_latest=1", (int(user_id),))
    return int(cur.fetchone()["n"])


def update_title(build_id: int, owner_user_id: int,
                 title: str) -> bool:
    """Rename a saved build. Owner-only. Per memory feature-site-share-builds
    the title is sticky on the lineage — updating it changes the title
    on the LATEST version row (the one /my-builds and /b/<code> show
    by default); older versions keep their historical titles.

    Returns True on update, False on not-owned / not-found / empty title."""
    title = (title or "").strip()[:120]
    if not title or not build_id or not owner_user_id:
        return False
    cur = get_db().cursor()
    cur.execute(
        "UPDATE build SET title=%s, updated=NOW() "
        "WHERE id=%s AND owner_user_id=%s",
        (title, int(build_id), int(owner_user_id)))
    get_db().commit()
    return cur.rowcount > 0
