"""Working-build session storage + summary (multi-draft, v1.5).

The session now holds **multiple working builds (drafts)** instead of
one. Schema:

  session['drafts'] = {
      "1": {"name": "Build #1", "items": {parts_id_str: qty, ...}},
      "2": {"name": "Build #2", "items": {...}},
      ...
  }
  session['active']  = "1"   # slot id of the currently-active draft
  session['next_n']  = 3     # monotonic counter for naming new drafts

Notes:
  - Slot ids are stable through deletes — if "2" is deleted, the
    next new draft gets id "3" (`next_n` never decreases). Names match
    slot ids ("Build #N") so you never see two drafts both labeled
    Build #2 even after a delete.
  - Items inside each draft keep the same shape as the v1 single-build
    {parts_id: qty} map — the existing helpers just pivot on the
    active draft's items.
  - Soft cap = MAX_DRAFTS (currently 5). When at cap, `new_draft()`
    refuses; the UI surfaces "save/share or delete one first."
  - Migration from v1: an older session with the flat `session['build']`
    key (single build) is rewritten on first read into `{drafts: {"1":
    {name: "Build #1", items: <prev>}}, active: "1", next_n: 2}`. No
    user-visible disruption.

See site-ng/docs/build-feature-design.md and feature-site-share-builds
for the eventual v1b transition where a draft "saves" by being
persisted to the DB + minted a short URL.
"""

from flask import session

from .labels import group_by_section
from .queries import last_price_for_ids, parts_by_ids, price_history_for_ids
from .sparkline import sparkline_svg


MAX_DRAFTS = 5


# --------------------------------------------------------------------------- #
# session shape helpers
# --------------------------------------------------------------------------- #
def _ensure_session() -> None:
    """Lazily initialize / migrate the session's drafts state.

    - First time: create one empty Build #1 and make it active.
    - v1 legacy: if the old `session['build']` key is present, wrap it
      into a Build #1 draft and drop the old key.
    - Defensive: if `active` points to a missing slot, repoint at the
      lowest-numbered draft (or create a fresh one if drafts went empty).
    """
    if "drafts" not in session:
        # v1 legacy migration path
        legacy = session.get("build")
        if legacy and isinstance(legacy, dict):
            session["drafts"] = {"1": {"name": "Build #1", "items": legacy}}
            session["active"] = "1"
            session["next_n"] = 2
            session.pop("build", None)
        else:
            session["drafts"] = {"1": {"name": "Build #1", "items": {}}}
            session["active"] = "1"
            session["next_n"] = 2
        _touch()
        return

    if not session["drafts"]:
        # Drafts dict somehow emptied — spawn a fresh one
        n = session.get("next_n", 1)
        slot = str(n)
        session["drafts"] = {slot: {"name": f"Build #{n}", "items": {}}}
        session["active"] = slot
        session["next_n"] = n + 1
        _touch()
        return

    if session.get("active") not in session["drafts"]:
        session["active"] = next(iter(session["drafts"]))
        _touch()


def _touch() -> None:
    """Flask's session won't auto-detect mutations inside nested dicts —
    flag it modified so the cookie is re-signed on response."""
    session.modified = True


def _active_items() -> dict:
    """Return the active draft's items dict {parts_id_str: qty},
    mutable (modifications via the returned reference are persisted
    when `_touch()` is called)."""
    _ensure_session()
    return session["drafts"][session["active"]]["items"]


# --------------------------------------------------------------------------- #
# item mutation — operates on the active draft
# --------------------------------------------------------------------------- #
def add_to_build(pid: int) -> int:
    items = _active_items()
    k = str(int(pid))
    items[k] = items.get(k, 0) + 1
    _touch()
    return items[k]


def remove_from_build(pid: int) -> None:
    items = _active_items()
    items.pop(str(int(pid)), None)
    _touch()


def decrement_in_build(pid: int) -> int:
    items = _active_items()
    k = str(int(pid))
    if k not in items:
        return 0
    items[k] -= 1
    if items[k] <= 0:
        del items[k]
        _touch()
        return 0
    _touch()
    return items[k]


def clear_build() -> None:
    """Clear the active draft's items AND its saved-build linkage —
    a wiped draft no longer represents the lineage it was associated
    with, so the next save starts a fresh lineage."""
    _ensure_session()
    d = session["drafts"][session["active"]]
    d["items"] = {}
    d.pop("saved_code", None)
    d.pop("saved_build_id", None)


def refresh_draft_names_for_code(code: str, new_name: str) -> int:
    """Update the `name` of any draft in the current session that
    links to the given saved-build code, so a rename on the saved
    record propagates to its working copies without requiring the
    user to re-Edit.

    Scoped to THIS request's session only (Flask sessions are
    per-cookie / per-user). Other users with drafts linking the
    same code see the new name lazily — next time their Edit
    re-hits load_into_draft, which now refreshes from
    head.title too (drafts/saved model reshape follow-up
    2026-05-27).

    Returns the number of draft slots updated.
    """
    _ensure_session()
    updated = 0
    for d in session["drafts"].values():
        if d.get("saved_code") == code and d.get("name") != new_name:
            d["name"] = new_name
            updated += 1
    if updated:
        _touch()
    return updated


def reset_active_draft_after_save() -> None:
    """After a successful Save / Update of the active draft, return
    the slot to fresh-empty state: no items, no saved_code linkage,
    name reset to a new "Build #N" default. The slot is FREED for
    new work; the saved data lives at /b/<code> + on /my-builds.

    Different from clear_build() which preserves the slot's user-
    typed name. After Save the user is "done" with this working
    state; treating the slot as a brand-new draft is the right
    affordance. Mike's drafts/saved model reshape 2026-05-27."""
    _ensure_session()
    slot = session["active"]
    n = session.get("next_n", 1)
    session["drafts"][slot] = {
        "name": f"Build #{n}",
        "items": {},
    }
    session["next_n"] = n + 1
    _touch()
    _touch()


# --------------------------------------------------------------------------- #
# draft (slot) management
# --------------------------------------------------------------------------- #
def list_drafts() -> list:
    """Return [{slot, name, count, total, is_active}, ...] in slot-id
    order. `total` is computed from CURRENT parts.price (so an OOS
    item still contributes — same convention as build_summary's
    `total`). Used by the drafts strip at the top of /build."""
    _ensure_session()
    drafts = session["drafts"]
    active = session["active"]
    # Collect all parts ids across all drafts for a single batched
    # lookup; cheaper than N lookups per draft.
    all_ids = set()
    for d in drafts.values():
        all_ids.update(int(k) for k in d["items"].keys())
    pmap = parts_by_ids(list(all_ids)) if all_ids else {}
    out = []
    for slot, d in drafts.items():
        count = sum(int(q) for q in d["items"].values())
        total = 0.0
        for pid_s, qty in d["items"].items():
            row = pmap.get(int(pid_s))
            if row:
                total += float(row["price"] or 0) * int(qty)
        saved_code = d.get("saved_code")
        # "(editing)" suffix on the display name when a draft is
        # tracking a saved build. Visually disambiguates working
        # copies from fresh drafts — Mike's drafts/saved model
        # reshape 2026-05-27: "i dont want to be confused as to why
        # a saved build is in my drafts at any time." The underlying
        # name stays the saved-build's title; this only changes
        # display in nav surfaces (chip, /my-builds drafts section).
        display_name = (f"{d['name']} (editing)"
                        if saved_code else d["name"])
        out.append({
            "slot": slot, "name": d["name"],
            "display_name": display_name,
            "count": count,
            "total": round(total, 2), "is_active": slot == active,
            # saved_code retained for the 💾 link in the chip
            # dropdown's secondary line. The "(editing)" suffix is
            # the primary signal; the secondary link gives the path
            # to the underlying saved build.
            "saved_code": saved_code,
        })
    return out


def new_draft() -> dict:
    """Create a new empty draft and make it active. Returns
    {ok: bool, slot, message}. Refuses past MAX_DRAFTS."""
    _ensure_session()
    if len(session["drafts"]) >= MAX_DRAFTS:
        return {"ok": False, "slot": None,
                "message": (f"You can have up to {MAX_DRAFTS} drafts at "
                            f"once. Share/save or delete one first.")}
    n = session["next_n"]
    slot = str(n)
    session["drafts"][slot] = {"name": f"Build #{n}", "items": {}}
    session["active"] = slot
    session["next_n"] = n + 1
    _touch()
    return {"ok": True, "slot": slot, "message": f"Created Build #{n}"}


def switch_draft(slot: str) -> bool:
    """Switch the active draft. Returns True on success, False if the
    requested slot doesn't exist."""
    _ensure_session()
    if slot in session["drafts"]:
        session["active"] = slot
        _touch()
        return True
    return False


def delete_draft(slot: str) -> dict:
    """Delete a draft entirely. If it was active, switch to any other
    remaining draft (or create a new empty one if it was the last)."""
    _ensure_session()
    if slot not in session["drafts"]:
        return {"ok": False, "message": "No such draft"}
    was_active = session["active"] == slot
    name = session["drafts"][slot]["name"]
    del session["drafts"][slot]
    if was_active:
        if session["drafts"]:
            session["active"] = next(iter(session["drafts"]))
        else:
            # Last draft gone — spawn a fresh empty one so the UI
            # always has something to render
            n = session["next_n"]
            new_slot = str(n)
            session["drafts"][new_slot] = {"name": f"Build #{n}",
                                            "items": {}}
            session["active"] = new_slot
            session["next_n"] = n + 1
    _touch()
    return {"ok": True, "message": f"Deleted {name}"}


def rename_draft(slot: str, name: str) -> dict:
    """Rename a working draft. The working surface otherwise auto-names
    drafts 'Build #N' and intentionally doesn't let them be renamed —
    custom names are a SIGNED-IN perk (the route is login-gated; this fn
    is pure session state). Trims + caps to 60 chars; empty is rejected."""
    _ensure_session()
    if slot not in session["drafts"]:
        return {"ok": False, "message": "No such draft"}
    name = (name or "").strip()[:60]
    if not name:
        return {"ok": False,
                "message": "Pick a name with at least one character."}
    session["drafts"][slot]["name"] = name
    _touch()
    return {"ok": True, "message": "Renamed"}


def can_add_draft() -> bool:
    _ensure_session()
    return len(session["drafts"]) < MAX_DRAFTS


# --------------------------------------------------------------------------- #
# build_summary — same shape as v1a, scoped to the active draft + drafts list
# --------------------------------------------------------------------------- #
def build_summary() -> dict:
    """Enriched view of the ACTIVE draft for templates. Also carries
    `drafts` (the list-of-drafts overview for the strip) and `name`
    (the active draft's display name, used by the header chip).

    Shape stays the same as v1 (lines/by_type/by_section/count/total/...)
    so the existing build_items partial keeps working unchanged. Only
    NEW keys at the top level: `drafts`, `name`, `slot`, `can_add_draft`.
    """
    _ensure_session()
    active_slot = session["active"]
    active = session["drafts"][active_slot]
    bmap = active["items"]
    count = sum(int(v) for v in bmap.values())

    # Empty active-draft path — same schema as the populated path
    if not bmap:
        return _empty_summary(active_slot, active["name"])

    ids = [int(k) for k in bmap.keys()]
    parts_map = parts_by_ids(ids)
    # Full history → drives the build-value time series at the bottom
    # of /build (where the user has consciously asked to see depth).
    history_map = price_history_for_ids(ids)
    last_price_map = last_price_for_ids(ids)
    # Per-line sparkline = same 90-day window as /browse cards, so
    # rows in the build list stay visually comparable to each other
    # AND to anything the user just hovered on /browse. window_start
    # is passed into sparkline_svg, which handles filtering + the
    # dotted-leading + solid-trailing render itself. For parts with
    # no in-window history (price has been stable for >90 days), we
    # synthesize a flat-at-current-price 2-point anchor so the line
    # stays visible — see the equivalent fallback in views/main.py.
    from datetime import date, datetime, timedelta
    _today_d = date.today()
    _spark_window_start = _today_d - timedelta(days=90)
    _spark_ws_dt = datetime.combine(_spark_window_start, datetime.min.time())
    _spark_today_dt = datetime.combine(_today_d, datetime.min.time())

    lines, by_type = [], {}
    total = instock_total = 0.0
    any_oos = any_missing = False
    price_drops_count = price_rises_count = 0
    price_drops_amount = price_rises_amount = 0.0

    for pid_str, qty in bmap.items():
        pid = int(pid_str)
        p = parts_map.get(pid)
        if not p:
            any_missing = True
            line = {"id": pid, "qty": int(qty), "missing": True,
                    "subtotal": 0.0, "type": "_missing"}
            lines.append(line)
            by_type.setdefault("_missing", []).append(line)
            continue
        price = float(p["price"] or 0)
        subtotal = price * int(qty)
        total += subtotal
        if p["instock"]:
            instock_total += subtotal
        else:
            any_oos = True
        history = history_map.get(pid, [])
        lp = last_price_map.get(pid)
        delta = None
        prev_when = None
        if lp is not None:
            try:
                delta = price - float(lp["price"])
                prev_when = lp["updated"]
                if delta < 0:
                    price_drops_count += 1
                    price_drops_amount += -delta * int(qty)
                elif delta > 0:
                    price_rises_count += 1
                    price_rises_amount += delta * int(qty)
            except (TypeError, ValueError):
                pass
        line = dict(p)
        line["qty"] = int(qty)
        line["subtotal"] = subtotal
        line["missing"] = False
        line["price_points"] = history
        # Pass full history + window_start; sparkline_svg filters
        # internally and renders the dotted-leading + solid-trailing
        # form. Full history still flows through to the time-series
        # chart calculation below (uses history_map directly). For
        # items with no in-window history, synthesize a flat-at-
        # current-price anchor (same rationale as views/main.py).
        spark_input = history if any(
            pt["updated"].date() >= _spark_window_start for pt in history
        ) else [{"price": p["price"], "updated": _spark_ws_dt},
                {"price": p["price"], "updated": _spark_today_dt}]
        line["sparkline"] = sparkline_svg(spark_input,
                                          window_start=_spark_window_start,
                                          today=_today_d)
        line["prev_price"] = lp["price"] if lp else None
        line["prev_when"] = prev_when
        line["delta"] = delta
        lines.append(line)
        by_type.setdefault(p["type"], []).append(line)

    time_series = _build_value_series(history_map, bmap, parts_map)

    # Validate the saved-build association on every build_summary
    # call. The session field can go stale: user deleted the saved
    # build, lost ownership, or the build was wiped by some other
    # process. We resolve the saved_code → build row → check it
    # actually exists, and compute a has_changes_vs_saved flag so
    # the Update button can disable when there's nothing to save.
    saved_code = active.get("saved_code")
    saved_build_id = active.get("saved_build_id")
    saved_build_owner = None
    has_changes_vs_saved = True
    if saved_code:
        from . import saves as _saves
        head = _saves.get_by_code(saved_code)
        if not head:
            # Saved build was deleted — clear the stale association
            # so the buttons (and the chip badge) stop lying.
            active.pop("saved_code", None)
            active.pop("saved_build_id", None)
            session.modified = True
            saved_code = None
            saved_build_id = None
        else:
            saved_build_owner = head.get("owner_user_id")
            # Compare the draft to the lineage's CURRENT latest (head
            # may be an older version the user once forked from).
            root = head.get("root_build_id") or head["id"]
            from .db import get_db
            cur = get_db().cursor()
            cur.execute(
                "SELECT id FROM build "
                "WHERE root_build_id=%s AND is_latest=1", (root,))
            latest_row = cur.fetchone()
            if latest_row:
                latest_items = _saves.get_items(latest_row["id"])
                latest_bmap = _saves._items_to_bmap(latest_items)
                has_changes_vs_saved = (
                    _saves._fingerprint(bmap)
                    != _saves._fingerprint(latest_bmap))

    # Build compatibility check — pattern-based detection of likely
    # cross-part mismatches (e.g. .308 mag + 5.56 barrel, 9mm lower
    # + 5.56 upper). Non-blocking; the template renders these as a
    # warning banner above the items list. Computed here (not in the
    # template) so OOB swaps on /build/add etc. carry the updated
    # warnings with the items refresh — no stale banner after add.
    from .compatibility import check_build as _check_compat
    compat_warnings = _check_compat(lines)

    return {
        # active-draft data (v1 schema, unchanged for templates)
        "lines": lines, "by_type": by_type,
        "by_section": group_by_section(by_type),
        "count": count, "total": total, "instock_total": instock_total,
        "any_oos": any_oos, "any_missing": any_missing,
        "price_drops_count": price_drops_count,
        "price_drops_amount": price_drops_amount,
        "price_rises_count": price_rises_count,
        "price_rises_amount": price_rises_amount,
        "by_id": dict(bmap),
        "time_series": time_series,
        "compat_warnings": compat_warnings,
        # multi-draft additions
        "name": active["name"],
        # display_name adds the "(editing)" suffix when this draft is
        # linked to a saved build, so the chip's main pill + the page
        # title disambiguate working-copies from fresh drafts.
        "display_name": (f"{active['name']} (editing)"
                         if saved_code else active["name"]),
        "slot": active_slot,
        "drafts": list_drafts(),
        "can_add_draft": can_add_draft(),
        "max_drafts": MAX_DRAFTS,
        # saved-build linkage. Templates use these to decide which
        # Save/Update buttons to render and whether Update is enabled.
        "saved_code": saved_code,
        "saved_build_id": saved_build_id,
        "saved_build_owner": saved_build_owner,
        "has_changes_vs_saved": has_changes_vs_saved,
    }


def _empty_summary(active_slot: str, active_name: str) -> dict:
    """Schema-matched empty-active-draft return — every key the
    templates read is present, just zeroed/empty."""
    return {
        "lines": [], "by_type": {}, "by_section": group_by_section({}),
        "count": 0, "total": 0.0, "instock_total": 0.0,
        "any_oos": False, "any_missing": False,
        "price_drops_count": 0, "price_drops_amount": 0.0,
        "price_rises_count": 0, "price_rises_amount": 0.0,
        "by_id": {}, "time_series": [], "compat_warnings": [],
        "name": active_name, "display_name": active_name,
        "slot": active_slot,
        "drafts": list_drafts(), "can_add_draft": can_add_draft(),
        "max_drafts": MAX_DRAFTS,
        # Empty draft has no saved-build association by definition —
        # Clear-build wipes both items AND saved_code, and a freshly
        # created draft starts empty. Keys present so templates can
        # access them without `is defined` checks.
        "saved_code": None, "saved_build_id": None,
        "saved_build_owner": None, "has_changes_vs_saved": False,
    }


def _build_value_series(history_map: dict, bmap: dict,
                        parts_map: dict) -> list:
    """Compute the active kit's total value at each date when ANY item
    had a price observation.

    Each item contributes (price × qty) at every date in the series:
      - For dates >= its first observation: uses the most-recent-known
        price as of that date (real data).
      - For dates BEFORE its first observation: uses its FIRST-known
        price (backfilled flat). Without this backfill the chart shows
        a jarring vertical jump at each item's "joined the data" date.
        Option D in build-feature-design.md (dashed segment for the
        backfilled span) is the future refinement.

    The series ends at "today" with the item's CURRENT parts.price.
    """
    dates = set()
    for pid_str in bmap.keys():
        pid = int(pid_str)
        for point in history_map.get(pid, []):
            dates.add(point["updated"].date())
    if not dates:
        return []
    from datetime import date
    today = date.today()
    dates.add(today)
    ordered = sorted(dates)

    item_obs = {}
    for pid_str, qty in bmap.items():
        pid = int(pid_str)
        history = sorted(history_map.get(pid, []),
                         key=lambda p: p["updated"])
        obs = [(p["updated"].date(), float(p["price"])) for p in history]
        p_row = parts_map.get(pid)
        if p_row:
            curr_price = float(p_row["price"] or 0)
            if not obs or obs[-1][0] < today:
                obs.append((today, curr_price))
            else:
                obs[-1] = (today, curr_price)
        if not obs:
            continue
        item_obs[pid] = {"obs": obs, "qty": int(qty), "idx": 0,
                         "first_price": obs[0][1]}

    series = []
    for d in ordered:
        total = 0.0
        for state in item_obs.values():
            obs = state["obs"]
            while state["idx"] + 1 < len(obs) and obs[state["idx"] + 1][0] <= d:
                state["idx"] += 1
            if obs[0][0] <= d:
                price_at_d = obs[state["idx"]][1]
            else:
                price_at_d = state["first_price"]
            total += price_at_d * state["qty"]
        series.append({"date": d.isoformat(), "total": round(total, 2)})

    # Collapse consecutive-equal totals to TRANSITIONS. price_history carries a
    # row per legacy scan (see memory price-history-legacy-per-scan-rows), so the
    # raw series is mostly flat repeats (~hundreds of points). Keep the first
    # point, each point where the total actually changes, and ALWAYS the final
    # point (today) so the stepped time-axis line still runs to now instead of
    # ending at the last change date.
    if len(series) > 2:
        deduped = [series[0]]
        for pt in series[1:]:
            if deduped[-1]["total"] != pt["total"]:
                deduped.append(pt)
        if deduped[-1]["date"] != series[-1]["date"]:
            deduped.append(series[-1])
        series = deduped
    return series
