"""Working-build routes (v1.5 — multi-draft session, no DB writes yet).

The session holds up to MAX_DRAFTS working builds; one is active at a
time. All item ops (+Add, +/-, remove, clear) target the ACTIVE draft.
Switching, creating, and deleting drafts are explicit user actions.

htmx response pattern: every POST returns three concatenated fragments
(via _full_oob_response or _qty_response):
  - the add-button or drafts strip etc. (regular response body for
    callers that hx-target a specific element)
  - build_chip (OOB)
  - build_items (OOB) — which now also carries the time_series JSON
    and the drafts strip's container
The drafts strip is part of the build_items OOB swap, so any item op
or draft-management op refreshes the strip's counts/totals/active-mark
in place without a page reload.
"""

from flask import Blueprint, make_response, redirect, render_template, request

from .. import auth
from ..build import (add_to_build, build_summary, clear_build,
                     decrement_in_build, delete_draft, new_draft,
                     remove_from_build, rename_draft, switch_draft)

bp = Blueprint("build", __name__)


def _htmx() -> bool:
    return request.headers.get("HX-Request") == "true"


def _redirect_with_msg(msg: str = ""):
    """Non-htmx fallback for action POSTs."""
    return redirect("/build" + ("?msg=" + msg.replace(" ", "+") if msg else ""))


# Every page that hosts an add button renders it under one of these
# namespaces; the OOB response updates all of them so whichever copy is
# actually on the current page gets refreshed (an OOB swap targeting an id
# that isn't on the page is a harmless no-op). card + table coexist on the
# listing pages (CSS shows one); detail is the product page's single button.
_ADD_BUTTON_NS = ("card", "table", "detail")


def _both_add_buttons(pid: int, qty: int) -> str:
    """Render the add button for a given part under EVERY namespace
    (_ADD_BUTTON_NS), each with hx-swap-oob='true'. The listing pages render
    both parts_grid.html (cards) and parts_table.html (table) concurrently —
    CSS shows one — and the product detail page renders its own; the clicked
    button uses hx-swap='none', so this OOB set is what actually updates the
    visible state. Emitting all namespaces every time means a click anywhere
    keeps every on-page copy in sync, and unused ones no-op."""
    return "".join(
        render_template("partials/add_button.html",
                        id=pid, qty=qty, view_ns=ns, oob=True)
        for ns in _ADD_BUTTON_NS)


def _qty_response(pid: int, new_qty: int):
    """Shared htmx response for /build/add and /build/dec — returns
    OOB swaps for both card+table add buttons, the build chip, the
    build items, AND the header action row. The clicked button has
    hx-swap='none' so the main response body content is ignored; all
    updates flow through matching ids on the OOB elements.

    Header action row is included so the Update-saved-build button's
    disabled/enabled gating (driven by has_changes_vs_saved) reflects
    the new qty without a page reload. Without this, qty changes only
    refreshed chip + items; the header Save/Update buttons stayed at
    their initial-render state."""
    summary = build_summary()
    return (_both_add_buttons(pid, new_qty)
            + render_template("partials/build_chip.html", build=summary)
            + render_template("partials/build_items.html", build=summary)
            + render_template("partials/build_header_actions.html", build=summary))


def _render_buttons_oob(summary, raw_ids: str) -> str:
    """Render OOB add-button fragments for a comma-separated id list.
    Two fragments per part (card + table namespace) so both
    responsive copies stay in sync. Shared by /build/draft/* (one
    round-trip consolidation when switching/creating drafts) and the
    standalone /build/buttons-refresh endpoint."""
    if not raw_ids:
        return ""
    by_id = summary["by_id"]
    fragments, seen = [], set()
    for tok in raw_ids.split(","):
        tok = tok.strip()
        if not tok or tok in seen:
            continue
        seen.add(tok)
        try:
            pid = int(tok)
        except ValueError:
            continue
        qty = int(by_id.get(str(pid), 0))
        fragments.append(_both_add_buttons(pid, qty))
    return "".join(fragments)


def _full_oob_response():
    """Shared htmx response for draft-management ops (new/switch/delete)
    and clear/remove — no specific trigger element to replace, just
    OOB-swap chip + items so every surface stays in sync.

    When the request includes `visible_ids` (added by the client-side
    htmx:configRequest hook in base.html for any /build/draft/* call),
    we ALSO append OOB <add_button> fragments for those ids. That
    consolidates the previous two-sequential-roundtrip pattern (switch
    response + buttons-refresh response) into a single round-trip:
    chip + drafts strip + buttons all swap from one response."""
    summary = build_summary()
    out = (render_template("partials/build_chip.html", build=summary)
           + render_template("partials/build_items.html", build=summary)
           + render_template("partials/build_header_actions.html", build=summary))
    out += _render_buttons_oob(summary, request.form.get("visible_ids", ""))
    return out


# --------------------------------------------------------------------------- #
# Page
# --------------------------------------------------------------------------- #
@bp.route("/build")
def view():
    return render_template("build.html", build=build_summary())


# --------------------------------------------------------------------------- #
# Item ops (target the active draft)
# --------------------------------------------------------------------------- #
@bp.route("/build/add", methods=["POST"])
def add():
    pid = request.form.get("id", type=int)
    if not pid:
        return _redirect_with_msg()
    new_qty = add_to_build(pid)
    if _htmx():
        return _qty_response(pid, new_qty)
    return _redirect_with_msg()


@bp.route("/build/dec", methods=["POST"])
def dec():
    """Decrement qty by one — undoes a misclick or steps a multi-pick
    down. Removes the line entirely when qty drops to 0."""
    pid = request.form.get("id", type=int)
    if not pid:
        return _redirect_with_msg()
    new_qty = decrement_in_build(pid)
    if _htmx():
        return _qty_response(pid, new_qty)
    return _redirect_with_msg()


@bp.route("/build/remove", methods=["POST"])
def remove():
    pid = request.form.get("id", type=int)
    if pid:
        remove_from_build(pid)
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg()


@bp.route("/build/clear", methods=["POST"])
def clear():
    """Clear the active draft's items (NOT the draft itself)."""
    clear_build()
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg()


# --------------------------------------------------------------------------- #
# Draft management
# --------------------------------------------------------------------------- #
@bp.route("/build/draft/new", methods=["POST"])
def draft_new():
    res = new_draft()
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg(res.get("message", ""))


@bp.route("/build/draft/switch", methods=["POST"])
def draft_switch():
    slot = request.form.get("slot", "")
    switch_draft(slot)
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg()


@bp.route("/build/draft/delete", methods=["POST"])
def draft_delete():
    slot = request.form.get("slot", "")
    delete_draft(slot)
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg()


@bp.route("/build/draft/<slot>/rename", methods=["POST"])
def draft_rename(slot):
    """Rename a working draft — a SIGNED-IN perk. Anonymous users get the
    login teaser in the chip instead of this form; this server-side gate
    is the safety net behind it (bounce to login, HX-Redirect for htmx)."""
    if not auth.current_user():
        if _htmx():
            resp = make_response("", 401)
            resp.headers["HX-Redirect"] = "/login?next=/build"
            return resp
        return redirect("/login?next=/build")
    rename_draft(slot, request.form.get("name", ""))
    if _htmx():
        return _full_oob_response()
    return _redirect_with_msg()


@bp.route("/build/draft/<slot>/continue", methods=["POST"])
def draft_continue(slot):
    """Switch the active draft to `slot` and land on /build. Used by
    the drafts section on /my-builds (and any other surface where the
    user wants 'switch + go edit' in one click). Mirrors the
    /b/<code>/continue pattern for saved builds — explicit URL so
    bookmarks/back-button work naturally, and no htmx required."""
    switch_draft(slot)
    return redirect("/build")


# --------------------------------------------------------------------------- #
# /build/buttons-refresh — refresh visible +Add buttons after a draft change
# --------------------------------------------------------------------------- #
@bp.route("/build/buttons-refresh", methods=["POST"])
def buttons_refresh():
    """Standalone endpoint to re-render a batch of +Add buttons as OOB
    fragments reflecting the CURRENT active draft. NORMALLY not needed
    — the draft/new/switch/delete responses include button fragments
    inline (one round-trip consolidation via the client's
    htmx:configRequest hook). Kept around as a fallback / for future
    explicit-refresh needs.

    Input: form field `ids` = comma-separated parts.id values.
    Output: one OOB fragment per id (each carries hx-swap-oob="true").
    """
    return _render_buttons_oob(build_summary(),
                                request.form.get("ids", ""))
