"""View routes for saved builds — Save / Update / My Builds / public.

  POST /build/save           promote the active draft to a NEW lineage
  POST /build/save-update    add a new version to an existing lineage
                             (owner only; requires draft.saved_code)
  GET  /my-builds            list of the logged-in user's lineages
                             (latest version per lineage)
  GET  /b/<code>             public view of a specific version
  GET  /b/<code>/history     all versions of this lineage
  POST /build/<id>/delete    owner-only delete of the WHOLE lineage
  POST /build/<id>/claim     associate an anonymous lineage with user
  POST /b/<code>/fork        load this version into a draft slot
"""

from __future__ import annotations

from flask import (Blueprint, abort, flash, redirect, render_template,
                   request, session)

from .. import auth, saves
from ..queries import last_price_for_ids, parts_by_ids

bp = Blueprint("saves", __name__)


# --------------------------------------------------------------------------- #
# Save: new lineage
# --------------------------------------------------------------------------- #
@bp.route("/build/save", methods=["POST"])
def save_build():
    """Promote the active draft into a NEW saved-build lineage. The
    user-facing 'Save as build' (when nothing is associated) and
    'Save as new build' (explicit fork after Update) buttons both
    route here.

    Owned saves dedupe — if the user already has a lineage whose
    latest version matches these items exactly, returns the existing
    URL instead of minting a duplicate. Anonymous saves never dedupe.

    Anonymous-save handshake: when the user is NOT logged in the form
    must carry `anonymous=1`, which the anonymous-save modal sets when
    the user explicitly picks "Save anonymously". Direct POSTs without
    that flag (the symptom of a stale session — the user thinks they're
    logged in but server-side they aren't) are bounced to /login
    rather than silently minting an ownerless permanent build."""
    title = (request.form.get("title") or "").strip()
    user = auth.current_user()
    anonymous_ok = request.form.get("anonymous") == "1"
    if not user and not anonymous_ok:
        # No user AND no explicit anonymous-save intent. Two paths
        # land here:
        #   (a) Stale session — current_user() just self-healed and
        #       flashed its own message; we let that ride and just
        #       consume the flag so it doesn't haunt later requests.
        #   (b) Plain direct POST without going through the modal
        #       (e.g. someone curl'ing /build/save). Flash a generic
        #       hint and bounce to login.
        # In both cases the user lands on /login?next=/build with a
        # banner explaining what happened. Their draft survives the
        # round-trip (drafts live in the session cookie, which we
        # haven't wiped — only the auth keys did).
        if not session.pop("_stale_session", False):
            flash("Pick how you want to save: sign in first, or save "
                  "anonymously from the build page.", "warning")
        return redirect("/login?next=/build")
    owner_user_id = int(user["id"]) if user else None
    res = saves.save_new_lineage(
        title=title or None,
        owner_user_id=owner_user_id)
    if not res:
        return redirect("/build?msg=empty-build-not-saved")
    # Drafts/saved model reshape 2026-05-27: after Save the working
    # copy lives at /b/<code>; the draft slot is freed for new work.
    # Clears items + saved_code linkage + resets the name. If the
    # user wants to keep iterating, the chip's Saved section or
    # /my-builds gets them back into editing-mode with one click
    # (which allocates a fresh linked draft).
    from ..build import reset_active_draft_after_save
    reset_active_draft_after_save()
    if not user:
        flash("Build saved anonymously. Bookmark this URL. Only people "
              "with the link can find it.", "warning")
    return redirect(f"/b/{res['code']}")


# --------------------------------------------------------------------------- #
# Save-after-login: the "Sign in first" branch of the anonymous-save modal.
# --------------------------------------------------------------------------- #
@bp.route("/save-after-login")
def save_after_login():
    """Endpoint that the anonymous-save modal's "Sign in first" branch
    redirects to (via /login?next=/save-after-login). After the magic-
    link auth round-trip lands the user here, we auto-save their
    still-in-session draft as a NEW lineage attached to the now-logged-
    in user, then redirect to /b/<code>.

    GET (not POST) because the magic-link consume issues a 302 — that's
    what lands users here. There's no CSRF concern: the worst case
    is an attacker crafts a link that auto-saves the user's OWN draft,
    which is a slight UX annoyance, not a security issue."""
    user = auth.current_user()
    if not user:
        # The login round-trip didn't actually log them in — bounce
        # back through /login with the same destination.
        return redirect("/login?next=/save-after-login")
    res = saves.save_new_lineage(owner_user_id=int(user["id"]))
    if not res:
        flash("Your draft was empty. Nothing was saved.", "warning")
        return redirect("/build")
    # Post-save reset matches the other Save paths (drafts/saved
    # reshape 2026-05-27).
    from ..build import reset_active_draft_after_save
    reset_active_draft_after_save()
    flash("Signed in and saved your build to your account.", "success")
    return redirect(f"/b/{res['code']}")


# --------------------------------------------------------------------------- #
# Save: update existing lineage
# --------------------------------------------------------------------------- #
@bp.route("/build/save-update", methods=["POST"])
def save_update():
    """Mint a new version of the draft's associated lineage. Requires:
      - The draft has a saved_code (it was forked-from or last-saved-to
        a lineage).
      - The current user owns that lineage. Non-owners must Save-as-new.

    If draft items match the latest version exactly, no-op and return
    the existing URL (idempotent)."""
    user = auth.current_user()
    if not user:
        return redirect("/login?next=/build")
    from ..build import build_summary
    summary = build_summary()
    saved_code = summary.get("saved_code")
    if not saved_code:
        # Draft isn't associated; nothing to update — fall through to
        # creating a new lineage instead (safer than a 400).
        return redirect("/build?msg=no-saved-build-to-update")
    head = saves.get_by_code(saved_code)
    if not head or head["owner_user_id"] != user["id"]:
        # User doesn't own this — they can only Save-as-new.
        return redirect("/build?msg=not-owner-of-saved-build")
    # The lineage's CURRENT latest may have advanced since the user
    # last loaded it; we want to chain off the latest, not the head
    # they originally forked from.
    latest = _lineage_latest(head)
    title = (request.form.get("title") or summary.get("name") or "").strip()
    res = saves.save_update_lineage(latest, title=title or None)
    if not res:
        return redirect("/build?msg=empty-build-not-saved")
    # Same post-save reset as the new-lineage path: draft slot freed,
    # saved version lives at /b/<code>. User can re-enter editing
    # via the saved-build's Edit/Continue button if they want more
    # iterations.
    from ..build import reset_active_draft_after_save
    reset_active_draft_after_save()
    return redirect(f"/b/{res['code']}")


def _lineage_latest(any_version: dict) -> dict:
    """Given any version of a lineage, return the row with
    is_latest=1. Used to ensure Update chains off the current head
    rather than whichever version the user happens to be on."""
    from ..db import get_db
    root = any_version.get("root_build_id") or any_version["id"]
    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 root_build_id=%s AND is_latest=1 LIMIT 1",
        (root,))
    return cur.fetchone() or any_version


# --------------------------------------------------------------------------- #
# /my-builds
# --------------------------------------------------------------------------- #
@bp.route("/my-builds")
def my_builds():
    user = auth.current_user()
    if not user:
        return redirect("/login?next=/my-builds")
    lineages = saves.list_for_user(user["id"])
    # Working drafts (session-bound, this browser only) — show above
    # the saved-builds section so the user has one place to see and
    # resume any in-progress work. Mike 2026-05-27: replaces the
    # drafts strip on /build (now removed) as the "deep" management
    # surface; chip dropdown stays the "quick" switcher.
    from ..build import build_summary
    summary = build_summary()
    # Only include drafts that have any items — empty drafts are
    # noise on this page (they're noise everywhere; the chip
    # dropdown shows them but they don't deserve full rows here).
    # The slot identity is used by the Continue button to switch
    # active.
    drafts = [d for d in summary.get("drafts", []) if (d.get("count") or 0) > 0]
    # Active draft first, then by slot order, for consistency with
    # the chip dropdown's ordering.
    drafts.sort(key=lambda d: (not d.get("is_active"), d.get("slot")))
    return render_template("saves/my_builds.html",
                           user=user, lineages=lineages,
                           drafts=drafts)


@bp.route("/my-builds/lineage/<int:root_id>/history")
def lineage_history(root_id):
    """htmx fragment: expand a lineage row to show all its versions
    with diff summaries. Owner-gated — same as the rest of /my-builds."""
    user = auth.current_user()
    if not user:
        return redirect("/login?next=/my-builds")
    # Sanity: ensure the lineage's latest is owned by this user.
    versions = saves.get_versions(root_id)
    if not versions or versions[0].get("title") is None:
        # Cheap ownership proxy: fetch the latest version and check
        # owner. Use saves.get_by_id for the full row.
        pass
    # Decorate each version with its diff summary.
    decorated = []
    for v in versions:
        diff = saves.diff_against_parent(v["id"])
        v = dict(v)
        v["diff"] = diff
        decorated.append(v)
    return render_template("saves/_version_history.html",
                           versions=decorated)


# --------------------------------------------------------------------------- #
# /b/<code> — public view of a specific version, rich data
# --------------------------------------------------------------------------- #
@bp.route("/b/<code>")
@bp.route("/b/<code>/<slug>")
def public_view(code, slug=None):
    """Anonymous read-only view of a saved-build version. Same rich
    rendering as the /build page (sparklines, time-series chart,
    summary block) plus saved-specific affordances on top (share-URL
    card with clipboard copy, owner controls if applicable, fork
    button, version-history link when there's more than one version).

    URL handling: accepts both bare `/b/<code>` and slugged
    `/b/<code>/<slug>`. The slug is hybrid (user's title slugified
    if clean; parts-based fallback if profane/empty). Bare URLs and
    non-canonical slugs both 301-redirect to the canonical slug —
    so old links still work AND we converge everyone on a single
    canonical URL for SEO. See ngsite/build_url.py."""
    head = saves.get_by_code(code)
    if not head:
        abort(404)
    items = saves.get_items(head["id"])

    # Compute the canonical slug; redirect to it if the request used
    # the bare form or a stale slug (e.g. build was renamed since
    # the link was originally shared).
    from ..build_url import build_slug
    canonical_slug = build_slug(head.get("title"), items)
    if slug != canonical_slug:
        return redirect(f"/b/{code}/{canonical_slug}", code=301)

    # Live data for items still in the catalog
    live_ids = [int(it["parts_id"]) for it in items if it["parts_id"]]
    parts_map = parts_by_ids(live_ids) if live_ids else {}
    last_price_map = last_price_for_ids(live_ids) if live_ids else {}

    # Per-line sparklines + decorations — same shape as build_items.html
    # so we can reuse the partial.
    from datetime import date, datetime, timedelta
    from ..queries import price_history_for_ids
    from ..sparkline import sparkline_svg
    from ..labels import group_by_section

    history_map = (price_history_for_ids(live_ids) if live_ids else {})
    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())

    decorated, by_type = [], {}
    total_at_save = total_now = instock_now = 0.0
    any_oos = any_missing = False
    price_drops_count = price_rises_count = 0
    price_drops_amount = price_rises_amount = 0.0

    for it in items:
        row = dict(it)
        qty = int(row["qty"] or 1)
        at_save = float(row["price_at_add"] or 0)
        total_at_save += at_save * qty
        pid = row["parts_id"]
        live = parts_map.get(pid) if pid else None
        if live is None:
            any_missing = True
            row["missing"] = True
            row["price"] = at_save
            row["instock"] = 0
            row["sparkline"] = ""
            total_now += at_save * qty   # snapshot fallback
        else:
            row["missing"] = False
            row["price"] = float(live["price"] or 0)
            row["instock"] = bool(live["instock"])
            row.update({k: live[k] for k in ("type", "company",
                                              "description", "url",
                                              "img") if k in live})
            total_now += row["price"] * qty
            if row["instock"]:
                instock_now += row["price"] * qty
            else:
                any_oos = True
            # Sparkline rendering (same 90-day window as /browse / /build)
            history = history_map.get(pid, [])
            spark_input = (history if any(
                pt["updated"].date() >= spark_window_start
                for pt in history) else [
                    {"price": row["price"], "updated": spark_ws_dt},
                    {"price": row["price"], "updated": spark_today_dt}])
            row["sparkline"] = sparkline_svg(
                spark_input, window_start=spark_window_start,
                today=today_d)
            # Delta vs last_price
            lp = last_price_map.get(pid)
            if lp:
                row["delta"] = row["price"] - float(lp["price"])
                row["prev_price"] = lp["price"]
                row["prev_when"] = lp["updated"]
                if row["delta"] < 0:
                    price_drops_count += 1
                    price_drops_amount += -row["delta"] * qty
                elif row["delta"] > 0:
                    price_rises_count += 1
                    price_rises_amount += row["delta"] * qty
            else:
                row["delta"] = None
                row["prev_price"] = None
                row["prev_when"] = None
        row["qty"] = qty
        row["subtotal"] = row["price"] * qty
        decorated.append(row)
        by_type.setdefault(row.get("type", "_missing"), []).append(row)

    user = auth.current_user()
    is_owner = bool(user and head["owner_user_id"] == user["id"])
    is_anonymous_lineage = head["owner_user_id"] is None
    # Claim is gated on (a) anonymous lineage, (b) this browser has
    # proof it saved the build (see saves.browser_has_claim_proof).
    # The user-is-logged-in part isn't checked here — the banner
    # branches on `user` separately to render "Sign in to claim" vs.
    # "Claim for X →".
    has_claim_proof = (is_anonymous_lineage
                        and saves.browser_has_claim_proof(head["code"]))
    is_claimable = bool(user and is_anonymous_lineage and has_claim_proof)

    # Version count + the latest version's code (used by the
    # "view latest" link when the user lands on a historic version).
    n_versions = 1
    latest_code = head["code"]
    if head.get("root_build_id"):
        versions = saves.get_versions(head["root_build_id"])
        n_versions = len(versions)
        for v in versions:
            if v["is_latest"]:
                latest_code = v["code"]
                break

    # Compatibility check — same heuristic as /build (memory:
    # feature-build-compatibility-checker). Pure read-only inspection
    # of the decorated lines; non-blocking warning if anything looks
    # off. Defined here on the public-view path because public_view
    # builds its own line list rather than going through
    # build_summary().
    from ..compatibility import check_build as _check_compat
    compat_warnings = _check_compat(decorated)

    # SEO data — see ngsite/build_url.py + docs/seo.md §B. Computed
    # here rather than in the template because is_profane() loads a
    # word list (cache + cheap, but still cleaner to centralize).
    from ..build_url import (is_profane, og_title_for,
                              meta_description_for)
    title_is_profane = is_profane(head.get("title"))
    og_title = og_title_for(head, decorated)
    seo_description = meta_description_for(head, decorated, total=total_now)

    # Build-value-over-time series for the Chart.js panel — same computation as
    # the active /build page, reusing the history/parts data already fetched
    # above (delisted items are skipped inside _build_value_series). Passed as
    # `build.time_series` so the shared build_chart.html partial works as-is.
    from ..build import _build_value_series
    bmap = {int(it["parts_id"]): int(it["qty"] or 1)
            for it in items if it["parts_id"]}
    time_series = _build_value_series(history_map, bmap, parts_map)

    return render_template(
        "saves/public_view.html",
        chart_series=time_series,  # NOT `build` — that's a global context var
                                   # (active draft) the header reads for its name
        head=head, items=decorated, by_section=group_by_section(by_type),
        total_at_save=total_at_save, total_now=total_now,
        instock_now=instock_now,
        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,
        compat_warnings=compat_warnings,
        n_versions=n_versions, latest_code=latest_code,
        is_owner=is_owner, is_claimable=is_claimable,
        is_anonymous_lineage=is_anonymous_lineage,
        has_claim_proof=has_claim_proof,
        canonical_slug=canonical_slug,
        title_is_profane=title_is_profane,
        og_title=og_title, seo_description=seo_description)


# --------------------------------------------------------------------------- #
# Delete (owner-only, deletes the entire lineage)
# --------------------------------------------------------------------------- #
@bp.route("/build/<int:build_id>/delete", methods=["POST"])
def delete_build(build_id):
    user = auth.current_user()
    if not user:
        return redirect("/login?next=/my-builds")
    head = saves.get_by_id(build_id)
    if not head:
        return redirect("/my-builds")
    root = head.get("root_build_id") or head["id"]
    saves.delete_lineage(root, user["id"])
    return redirect("/my-builds")


# --------------------------------------------------------------------------- #
# Claim an anonymous lineage
# --------------------------------------------------------------------------- #
@bp.route("/build/<int:build_id>/claim", methods=["POST"])
def claim_build(build_id):
    user = auth.current_user()
    if not user:
        # Send them to login; preserve where to come back to.
        code = request.form.get("code") or ""
        return redirect(f"/login?next=/b/{code}")
    # Proof-of-ownership gate: only the browser that originally saved
    # this anonymous build (whose signed session cookie carries the
    # code in `anon_saves` or on a draft) can claim it. Without this
    # check, anyone learning the share URL could race-claim before the
    # legitimate creator. See security review H3.
    head = saves.get_by_id(build_id)
    code = request.form.get("code") or (head["code"] if head else "")
    if not head:
        flash("That build no longer exists.", "warning")
        return redirect("/my-builds")
    if not saves.browser_has_claim_proof(head["code"]):
        flash("Only the browser that originally saved this anonymous "
              "build can claim it. If you saved it from a different "
              "browser, sign in there to claim. If you cleared cookies, "
              "the build can no longer be claimed. Use \"Use as a "
              "starting point\" to fork it into a new build of your own.",
              "warning")
        return redirect(f"/b/{code}" if code else "/my-builds")
    saves.claim(build_id, user["id"])
    return redirect(f"/b/{code}" if code else "/my-builds")


# --------------------------------------------------------------------------- #
# Continue editing — load a saved version into a draft, preserving the
# saved_code link so the next Save mints a NEW VERSION of THIS lineage.
# Owner-only at the route level; non-owners get bounced to fork.
# --------------------------------------------------------------------------- #
@bp.route("/b/<code>/continue", methods=["POST"])
def continue_editing(code):
    head = saves.get_by_code(code)
    if not head:
        abort(404)
    user = auth.current_user()
    # Optional slot= form param — present when the slot-picker
    # confirmed which slot to replace. Otherwise we auto-pick (or
    # bounce to the picker when slots are full).
    forced_slot = (request.form.get("slot") or "").strip() or None

    if not user or head["owner_user_id"] != user["id"]:
        # Non-owners get the fork path (preserve_link=False) — no
        # Update permission on someone else's lineage.
        flash("You can't continue editing someone else's build. "
              "Loaded as a starting point for a new build of your own.",
              "warning")
        summary = saves.load_into_draft(code, preserve_link=False,
                                        slot=forced_slot)
        if not summary:
            # Drafts full + no forced slot. Show the picker.
            return redirect(f"/b/{code}/pick-slot?mode=fork")
        return redirect("/build")

    # Owner path — preserve_link=True so Save updates this lineage.
    summary = saves.load_into_draft(code, preserve_link=True,
                                    slot=forced_slot)
    if not summary:
        # Drafts full + no forced slot — show the picker.
        return redirect(f"/b/{code}/pick-slot?mode=continue")
    # Orient the user on landing. The chip on the header silently
    # switched to this build's working area, and the user may not
    # realize they can now Browse for more parts to add. Flash a
    # one-time confirmation that says both: this IS now your working
    # build, AND the path to add to it. Uses the "success-long"
    # category so flashes.html gives it the 12-second timeout —
    # this message is multi-sentence and the user benefits from
    # extra time to read.
    title = head.get("title") or "this build"
    flash(f"Now editing “{title}” in your working area. "
          "Adjust quantities below, Browse to add more parts, or "
          "click Update saved build when you're done.",
          "success-long")
    return redirect("/build")


# --------------------------------------------------------------------------- #
# Slot picker — shown when the user tries to Continue editing a saved
# build but all draft slots are occupied with items.
# --------------------------------------------------------------------------- #
@bp.route("/b/<code>/pick-slot")
def pick_slot(code):
    """Render a chooser when /b/<code>/continue can't auto-allocate
    a draft slot. Lists the current drafts (with name + count + total)
    so the user can pick WHICH one to replace, then a final submit
    POSTs back to /b/<code>/continue with slot=<chosen> to do the
    load."""
    head = saves.get_by_code(code)
    if not head:
        abort(404)
    from ..build import list_drafts
    drafts = list_drafts()
    mode = (request.args.get("mode") or "continue").strip()
    # title for the prompt — saved-build's display title or the code
    title = head.get("title") or f"build /{code}"
    return render_template("saves/pick_slot.html",
                           head=head, code=code, drafts=drafts,
                           mode=mode, title=title)


# --------------------------------------------------------------------------- #
# Fork — same loader but WITHOUT preserving the saved_code link.
# Save creates a new lineage owned by the forker. Right action for
# non-owners ("use this as a starting point") and for owners who
# explicitly want a derivative rather than a new version of the same.
# --------------------------------------------------------------------------- #
@bp.route("/b/<code>/fork", methods=["POST"])
def fork(code):
    # Optional slot= override (slot-picker path) — same as
    # /b/<code>/continue but preserve_link=False for the fork.
    forced_slot = (request.form.get("slot") or "").strip() or None
    # Confirm the build exists before any session mutation so a
    # bad code returns 404 cleanly even with an explicit slot.
    if not saves.get_by_code(code):
        abort(404)
    summary = saves.load_into_draft(code, preserve_link=False,
                                    slot=forced_slot)
    if not summary:
        # Drafts full and no forced slot — same slot-picker page as
        # the continue path, with mode=fork so the prompt copy
        # matches the user's intent.
        return redirect(f"/b/{code}/pick-slot?mode=fork")
    return redirect("/build")


# --------------------------------------------------------------------------- #
# Save-form modal — renders the rename-at-save inline form via htmx.
# --------------------------------------------------------------------------- #
@bp.route("/build/save-form")
def save_form():
    """Render the save-form modal (rename + commit). Called by htmx
    from the Save / Save-as-new buttons on /build. The form POSTs to
    /build/save (new lineage) or /build/save-update (new version).

    Mode comes from ?mode=new|update|new-from-saved:
      - new: not currently linked to anything — first-time save.
      - new-from-saved: linked to a saved build (owner), but user
        explicitly picked "Save as new build" rather than Update.
        Effect = same POST as 'new'.
      - update: linked + owned + user picked Update. POSTs to
        /build/save-update.
    The mode shapes the modal copy + suggested default name.

    Stale-saved-code downgrade: build_summary self-heals a draft whose
    saved_code points at a deleted build (clears the code). When this
    happens between page-render-time (when the button was rendered) and
    form-load-time (this call), the requested mode/copy no longer makes
    sense — there's no linked build to reference. Downgrade to 'new' so
    we render the first-time-save copy instead of dangling references
    to a build that doesn't exist."""
    from ..build import build_summary
    mode = request.args.get("mode", "new")
    summary = build_summary()
    if mode in ("update", "new-from-saved") and not summary.get("saved_code"):
        mode = "new"
    return render_template("saves/_save_modal.html",
                           mode=mode, build=summary)


# --------------------------------------------------------------------------- #
# Rename a saved build (owner-only)
# --------------------------------------------------------------------------- #
@bp.route("/build/<int:build_id>/rename", methods=["POST"])
def rename_build(build_id):
    user = auth.current_user()
    if not user:
        return redirect("/login?next=/my-builds")
    new_title = (request.form.get("title") or "").strip()
    if not new_title:
        flash("Pick a name with at least one character.", "warning")
        return redirect(request.referrer or "/my-builds")
    ok = saves.update_title(build_id, int(user["id"]), new_title)
    if not ok:
        flash("Couldn't rename that build. It may not be yours.", "warning")
    else:
        flash(f"Renamed to '{new_title}'.", "success")
        # Propagate the new title to any draft in THIS session that's
        # linked to this build. Without this, the chip's drafts
        # section would keep showing the old name until the user
        # re-Edits the build (load_into_draft would refresh lazily).
        # Drafts/saved model reshape follow-up 2026-05-27.
        head = saves.get_by_id(build_id)
        if head and head.get("code"):
            from ..build import refresh_draft_names_for_code
            refresh_draft_names_for_code(head["code"], new_title)
    return redirect(request.referrer or "/my-builds")
