"""Main routes. Server-rendered pages + an htmx fragment endpoint so
filtering updates without a full reload (while the full pages keep real
crawlable URLs)."""

from datetime import date, timedelta
from urllib.parse import urlencode

from flask import (Blueprint, abort, make_response, redirect,
                   render_template, request)

from ..queries import (DEFAULT_SORT, LANDING_SORT, MAX_RECENT_PAGES, PAGE_SIZE,
                       companies, count_in_stock, count_recent_missed,
                       count_recent_new, count_recent_popular,
                       count_recent_pricedrops, in_stock,
                       last_price_for_ids, list_types,
                       list_types_grouped, price_history_for_ids,
                       recent_companies, recent_missed, recent_new,
                       recent_popular, recent_pricedrops, stockometer)
from ..labels import TYPE_LABELS, canonical_type
from ..sparkline import sparkline_svg

# Days of history covered by the at-a-glance sparkline on /browse +
# /build. Locked window so all sparklines are visually comparable
# regardless of how much real history each part has accumulated.
# Full-history visualization lives on the eventual /product/<id>
# page (deferred — see todo).
SPARKLINE_WINDOW_DAYS = 90

bp = Blueprint("main", __name__)


@bp.route("/faq")
def faq():
    """Frequently asked questions — static content page ported from
    legacy /faq.htm with ng-specific updates (build feature, email
    use, AR-10 mention). Reached via the desktop footer link and the
    mobile More sheet."""
    return render_template("faq.html")


@bp.route("/resources")
def resources():
    """Curated AR-15/AR-10 resources — forums, guides, FFL locators.
    Ported from legacy /resources.htm. Static. Retailer reviews
    section from legacy is intentionally NOT ported — those still
    live on the legacy /compfeedback_<retailer>.htm pages."""
    return render_template("resources.html")


@bp.route("/terms")
def terms():
    """Terms of Service + Privacy Policy. Ported from legacy
    /tos.htm with the privacy policy substantially rewritten to be
    accurate about the magic-link auth flow + explicit about
    email-use limits (no unsolicited mail, no sharing/selling)."""
    return render_template("terms.html")


@bp.route("/changelog")
def changelog():
    """What's new on the site. Server-rendered from the YAML source
    at site-ng/data/changelog.yml — see ngsite/changelog.py for the
    window logic (30d or last 3 dates, whichever covers more).
    `today` is passed in so the template can label Today / Yesterday
    / N days ago without needing to import datetime in Jinja."""
    from ..changelog import windowed, newest_date
    return render_template("changelog.html",
                           entries=windowed(),
                           newest=newest_date(),
                           today=date.today())


@bp.route("/")
def index():
    # FUTURE: interactive AR silhouette nav becomes the hero element
    # here (memory: feature-site-interactive-ar-silhouette-nav). Until
    # then, the "How it works" strip carries the positioning load.
    # retailer_count is a real number rather than a hardcoded "N" so
    # the homepage stays honest as the company list grows. companies()
    # returns retailers with any in-stock rows; len() of that is the
    # right denominator for "we track N retailers right now".
    # Home is a launchpad: hero + the three doors + the build banner +
    # how-it-works. No category lists, product strips, or stockometer, so it
    # renders with zero DB queries. Everything else is one click deeper (those
    # pages carry the side nav).
    return render_template("index.html")


def _enrich_for_browse(parts):
    """Enrich each parts row with price-history signals for the card:
      - sparkline: pre-rendered SVG of the part's full history.
      - delta: current price - last_price.price (float, None if no
        last_price row for this part).
      - prev_price / prev_when: the previous-price + timestamp that
        the delta is measured against (None when no last_price).

    The delta text next to the sparkline is what makes the sparkline
    *legible* — without it the sparkline reads as decoration; with
    it the user grasps "this graphic is about price." Same pattern
    as the /build line items.

    Two batched queries (price_history + last_price), both indexed.
    """
    if not parts:
        return
    ids = [p["id"] for p in parts]
    # 90-day cap so all sparklines share the same x-axis scale —
    # see comments in queries.price_history_for_ids. Full history
    # lives on the future /product/<id> page.
    history_map = price_history_for_ids(ids,
                                        since_days=SPARKLINE_WINDOW_DAYS)
    last_price_map = last_price_for_ids(ids)
    from datetime import datetime
    today_d = date.today()
    window_start = today_d - timedelta(days=SPARKLINE_WINDOW_DAYS)
    # Synthetic anchors for parts with no in-window history. The
    # scanner only writes to price_history on CHANGE, so absence of
    # in-window rows means "price has been stable for >90 days" —
    # which is itself meaningful signal. Render a flat solid line at
    # the current price across the window so every card has a
    # sparkline and the grid stays visually consistent.
    ws_dt = datetime.combine(window_start, datetime.min.time())
    today_dt = datetime.combine(today_d, datetime.min.time())
    for p in parts:
        history = history_map.get(p["id"], [])
        if not history:
            history = [{"price": p["price"], "updated": ws_dt},
                       {"price": p["price"], "updated": today_dt}]
        p["sparkline"] = sparkline_svg(history,
                                        window_start=window_start,
                                        today=today_d)
        lp = last_price_map.get(p["id"])
        if lp is not None:
            try:
                p["delta"] = float(p["price"]) - float(lp["price"])
                p["prev_price"] = lp["price"]
                p["prev_when"] = lp["updated"]
            except (TypeError, ValueError):
                p["delta"] = None
                p["prev_price"] = None
                p["prev_when"] = None
        else:
            p["delta"] = None
            p["prev_price"] = None
            p["prev_when"] = None


def _browse_canonical_url(f, page=None):
    """Reconstruct the canonical /browse?... URL from a parsed filter
    dict. Used by browse_parts() to (a) redirect direct hits on the
    htmx fragment endpoint, and (b) tell htmx (via HX-Push-Url) what
    URL to put in the address bar — so a user's refresh always loads
    /browse (the full page), never /browse/parts (the fragment)."""
    params = []
    if f["sel_type"]:
        params.append(("type", f["sel_type"]))
    if f["q"]:
        params.append(("q", f["q"]))
    if f["price_min"] is not None:
        params.append(("price_min", str(int(f["price_min"]))))
    if f["price_max"] is not None:
        params.append(("price_max", str(int(f["price_max"]))))
    for c in f["companies_"]:
        params.append(("r", c))
    for c in f["excludes_"]:
        params.append(("rx", c))
    if f["sort"] and f["sort"] != _default_sort(f["sel_type"]):
        params.append(("sort", f["sort"]))
    p = page if page is not None else f.get("page", 1)
    if p and int(p) > 1:
        params.append(("page", str(int(p))))
    return "/browse" + ("?" + urlencode(params) if params else "")


def _default_sort(sel_type):
    """Context-dependent default sort. The bare /browse landing (no type) leads
    with LANDING_SORT ('newest' = fresh/restocked first); every other context
    (a selected category, build part-picking, fragments) uses DEFAULT_SORT
    ('price_desc' = substantial items first). Used for both the applied default
    and the canonical-URL 'is this the default?' check, so the two stay in sync."""
    return LANDING_SORT if not sel_type else DEFAULT_SORT


def _parse_filters(req):
    """Pull the secondary-filter state from the request query string.
    Returns a dict the view + template both consume so we have one
    source of truth on what counts as "an active filter".

    `companies_` is the include multi-value list — `?r=A&r=B` → `[A, B]`.
    `excludes_` is the exclude multi-value list — `?rx=X` → `[X]`, mapped
    to a server-side `company NOT IN (...)` clause.

    `?company=` is honored as an alias for `?r=` for ~30 days post-rename
    so any URLs already out in the wild (history, bookmarks, shared
    links) still filter correctly. Mike 2026-05-30. Drop the alias once
    we're confident nothing in the wild relies on it.

    Empty strings are dropped. `price_min`/`price_max` accept "" /
    "abc" gracefully (→ None) so a busted URL doesn't 500. `page` is
    clamped to >= 1; out-of-range is clamped to the last valid page
    by the view after counting."""
    def _num(v):
        if v in (None, ""):
            return None
        try:
            return float(v)
        except (TypeError, ValueError):
            return None
    def _page(v):
        try:
            return max(1, int(v or 1))
        except (TypeError, ValueError):
            return 1
    # Include set: prefer new `r=`, fall back to legacy `company=` if `r=`
    # is absent (don't merge both lists — a stale legacy URL replaced).
    includes = [c for c in req.args.getlist("r") if c]
    if not includes:
        includes = [c for c in req.args.getlist("company") if c]
    return {
        "sel_type":    req.args.get("type") or None,
        "companies_":  includes,
        "excludes_":   [c for c in req.args.getlist("rx") if c],
        "q":           (req.args.get("q") or "").strip(),
        "price_min":   _num(req.args.get("price_min")),
        "price_max":   _num(req.args.get("price_max")),
        "sort":        req.args.get("sort") or _default_sort(req.args.get("type") or None),
        "page":        _page(req.args.get("page")),
    }


def _browse_context(f, parts, total=None, companies_list=None):
    """Common /browse context: sidebar data + retailer list + filter
    state + pagination. Both the full page render and the htmx
    fragment endpoint pull from here to stay in sync.

    `total` is the full result count (pre-pagination) used for the
    "N results" label and the page-count math.

    `companies_list` overrides the retailer dropdown list — the recent
    /instock pages pass a window-scoped list (recent_companies) so the
    counts match the page instead of showing each retailer's whole
    in-stock catalog."""
    if total is None:
        total = len(parts)
    page_count = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)
    return dict(
        types=list_types(),
        # Retailer list scoped to the current type filter, with counts.
        # Note: this is the FULL retailer list for the type, NOT
        # narrowed by the in-flight company multi-select — that would
        # delete retailers from the list the moment a user picks one,
        # making it impossible to add a second. The count remains the
        # total-for-this-type so the user can see "Brownells (494)"
        # before deciding.
        companies=(companies_list if companies_list is not None
                   else companies(f["sel_type"])),
        parts=parts,
        sel_type=f["sel_type"], sel_companies=set(f["companies_"]),
        sel_excludes=set(f["excludes_"]),
        sel_q=f["q"], sel_price_min=f["price_min"],
        sel_price_max=f["price_max"], sel_sort=f["sort"],
        sel_page=f["page"],
        total_count=total, page_count=page_count, page_size=PAGE_SIZE,
        sections=list_types_grouped(),
        stockometer=stockometer())


def _clamp_page(f, total):
    """Clamp the requested page to [1, page_count] so an out-of-range
    `?page=99` doesn't render an empty grid with a nonsense "Page 99
    of 6" indicator. Mutates `f` in place and returns it."""
    page_count = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)
    f["page"] = min(max(1, f["page"]), page_count)
    return f


@bp.route("/browse")
def browse():
    f = _parse_filters(request)
    total = count_in_stock(
        type_=f["sel_type"], companies_=f["companies_"],
        excludes_=f["excludes_"],
        q=f["q"], price_min=f["price_min"],
        price_max=f["price_max"])
    _clamp_page(f, total)
    parts = in_stock(
        type_=f["sel_type"], companies_=f["companies_"],
        excludes_=f["excludes_"],
        q=f["q"], price_min=f["price_min"],
        price_max=f["price_max"], sort=f["sort"],
        page=f["page"])
    _enrich_for_browse(parts)
    return render_template("browse.html",
                           **_browse_context(f, parts, total))


@bp.route("/report-category", methods=["POST"])
def report_category():
    """Visitor-submitted "this item is in the wrong category" report.
    Inserts into category_reports for human review on the dashboard.

    Rate-limited: one report per (IP, parts_id) per 24h. Honest dedupe
    against the same person spamming the same product; doesn't try to
    prevent rotating-IP abuse (not worth the complexity at this scale).

    Returns a small HTML fragment that replaces the modal body —
    success message or "already reported" — so the UX completes
    without a page reload."""
    from ..db import get_db
    pid = request.form.get("parts_id", type=int)
    suggested = (request.form.get("suggested") or "").strip() or None
    # X-Forwarded-For — read the RIGHT-most entry (closest to our
    # proxy = the trusted hop). The left-most entry is whatever the
    # client put there, so reading [0] would let an attacker spoof
    # the rate-limit key. Security finding M1.
    ip = (request.headers.get("X-Forwarded-For", "").split(",")[-1].strip()
          or request.remote_addr or "unknown")
    if not pid:
        return ('<p class="text-sm text-red-600">Missing parts id. '
                'Try refreshing the page.</p>')
    cur = get_db().cursor()
    # Look up the current type + url to snapshot at report time (so a
    # later parts purge / retype doesn't lose the report context).
    cur.execute("SELECT type, url FROM parts WHERE id=%s", (pid,))
    parts_row = cur.fetchone()
    if not parts_row:
        return ('<p class="text-sm text-red-600">'
                "That item isn't in our catalog anymore.</p>")
    # Rate-limit check.
    cur.execute(
        "SELECT COUNT(*) AS n FROM category_reports "
        "WHERE parts_id=%s AND reporter_ip=%s "
        "  AND reported_at > NOW() - INTERVAL 24 HOUR",
        (pid, ip))
    if int(cur.fetchone()["n"]) > 0:
        return _report_modal_done(
            "Already reported",
            "You've already reported this one in the last 24 hours. "
            "Thanks for the heads-up. We'll review.")
    cur.execute(
        "INSERT INTO category_reports "
        "  (parts_id, parts_url, current_type, suggested, reporter_ip) "
        "VALUES (%s, %s, %s, %s, %s)",
        (pid, parts_row["url"], parts_row["type"], suggested, ip))
    get_db().commit()
    return _report_modal_done(
        "Thanks for the report!",
        "We review these on a cadence and use them to feed the "
        "reclassifier. Reports with multiple voices float to the top.")


def _report_modal_done(title: str, body: str) -> str:
    """Small HTML fragment replacing the report-modal body on a
    successful (or short-circuited) submit. Includes a Close button
    that fires the modal's close() — same data-report-close hook the
    Cancel button uses in the default body."""
    return (
        # data-report-done lets base.js detect a COMPLETED report (this fragment
        # serves both the success + "already reported" cases) to drive the
        # after-N auto-dismiss (see base.js report-modal handler).
        '<div class="p-4 text-center" data-report-done>'
        f'<p class="font-bold mb-2">{title}</p>'
        f'<p class="text-sm text-gray-600 dark:text-gray-400 mb-3">{body}</p>'
        '<button type="button" data-report-close'
        ' class="px-3 py-1 text-sm bg-emerald-600 hover:bg-emerald-700 '
        'text-white rounded">Close</button>'
        "</div>")


def _duration_human(secs):
    """Compact "X ago" / "X total" formatting for the recent pages.
    None → "—". Negative / 0 → "just now". Tuned for at-a-glance scan
    rather than precision (e.g., 89 s reads "1m", not "1m 29s")."""
    if secs is None:
        return ""
    s = int(secs)
    if s <= 0:
        return "just now"
    if s < 60:
        return f"{s}s"
    if s < 3600:
        return f"{s // 60}m"
    if s < 86400:
        return f"{s // 3600}h"
    if s < 86400 * 14:
        return f"{s // 86400}d"
    if s < 86400 * 60:
        return f"{s // 86400 // 7}w"
    return f"{s // 86400 // 30}mo"


def _decorate_recent(parts):
    """Enrich recent-page rows: sparklines/deltas via _enrich_for_browse
    plus a human duration for whichever time field the page uses. Shared
    by the full-page render and the htmx fragment so they stay identical."""
    _enrich_for_browse(parts)
    for p in parts:
        if "since_added_secs" in p:
            p["since_added_human"] = _duration_human(p["since_added_secs"])
        if "since_oos_secs" in p:
            p["since_oos_human"] = _duration_human(p["since_oos_secs"])
        if "was_instock_secs" in p:
            p["was_instock_human"] = _duration_human(p["was_instock_secs"])
        if "since_drop_secs" in p:
            p["since_drop_human"] = _duration_human(p["since_drop_secs"])


def _recent_canonical_url(kind, f):
    """Canonical /instock/<kind>?<filters> URL (no sort) — the htmx
    HX-Push-Url target and the non-htmx redirect target for the fragment,
    so refresh / share / new-tab all land on the full page."""
    params = []
    if f["q"]:
        params.append(("q", f["q"]))
    if f["price_min"] is not None:
        params.append(("price_min", str(int(f["price_min"]))))
    if f["price_max"] is not None:
        params.append(("price_max", str(int(f["price_max"]))))
    for c in f["companies_"]:
        params.append(("r", c))
    for c in f["excludes_"]:
        params.append(("rx", c))
    if f["page"] > 1:
        params.append(("page", str(f["page"])))
    qs = urlencode(params)
    return "/instock/{}{}".format(kind, ("?" + qs) if qs else "")


def _saved_query_page(parts, total, page_kind, page_title, f,
                      page_blurb=None, empty_blurb=None):
    """Shared full-page render for the four /instock/<slug> pages.
    `f` is the parsed filter dict; these pages support the /browse-style
    retailer/price/search filters. SORT is not exposed (each page keeps
    its inherent order), so the template hides the sort control when
    page_kind is set."""
    _decorate_recent(parts)
    return render_template(
        "browse.html",
        **_browse_context(f, parts, total,
                          companies_list=recent_companies(page_kind)),
        page_kind=page_kind, page_title=page_title,
        page_blurb=page_blurb, empty_blurb=empty_blurb)


def _recent_route(count_fn, page_fn, kind, title, blurb=None, empty=None):
    """Shared boilerplate for the four /instock/<slug> routes:
    parse page, count for the paginator, clamp the page in range,
    fetch the slice, render. Each route is a thin call into this.

    The displayed `total` is capped at MAX_RECENT_PAGES[kind] *
    PAGE_SIZE — see the MAX_RECENT_PAGES rationale in queries.py.
    The cap applies to the paginator + the "N items" label only;
    we still call count_fn() to know when the actual data is sparser
    than the cap (e.g. only 12 popular items in 31 days → total=12,
    not 50)."""
    f = _parse_filters(request)
    parts, total, blurb = _recent_data(kind, count_fn, page_fn, f, blurb)
    return _saved_query_page(parts, total, kind, title, f,
                             page_blurb=blurb, empty_blurb=empty)


def _recent_data(kind, count_fn, page_fn, f, blurb):
    """Run a recent page's query with the parsed filters, applying the
    MAX_RECENT_PAGES cap to the total + paginator (the retailer-dropdown
    counts stay true window totals). Returns (parts, total, blurb); blurb
    gets a "(capped at N items)" note when the cap clipped the set. Shared
    by the full-page route (_recent_route) and the htmx fragment.

    Recent pages keep their inherent order (newest / most-clicked /
    biggest drop), so SORT is not passed through — only type / retailer /
    price / search filter the set via _filter_where."""
    filt = dict(type_=f["sel_type"], companies_=f["companies_"],
                excludes_=f["excludes_"], q=f["q"],
                price_min=f["price_min"], price_max=f["price_max"])
    max_pages = MAX_RECENT_PAGES.get(kind)   # None = no cap
    # Single-page Top-N (popular): page_fn LIMITs to PAGE_SIZE, so
    # len(parts) IS the total — skip the second (expensive join) count.
    if max_pages == 1:
        parts = page_fn(page=1, **filt)
        f["page"] = 1
        return parts, len(parts), blurb
    actual_total = count_fn(**filt)
    total = actual_total if max_pages is None else min(actual_total,
                                                       max_pages * PAGE_SIZE)
    if blurb and max_pages is not None and actual_total > total:
        blurb = "{} (capped at {} items)".format(blurb.rstrip("."), total)
    page_count = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)
    f["page"] = min(f["page"], page_count)
    parts = page_fn(page=f["page"], **filt)
    return parts, total, blurb


# kind -> (count_fn, page_fn, title, blurb, empty_blurb)
_RECENT_KINDS = {
    "new": (
        count_recent_new, recent_new, "Newest In-Stock",
        "Items that came back in stock or were seen for the first time "
        "in the last 7 days.", None),
    "missed": (
        count_recent_missed, recent_missed, "Recently Out of Stock",
        "Items that went out of stock in the last 7 days: what you missed "
        "(and might come back).",
        "Nothing's gone out of stock recently. Either supply is calm or "
        "our scanners are very efficient."),
    "popular": (
        count_recent_popular, recent_popular, "Popular In-Stock",
        "Top 50 most-clicked in-stock items over the last 31 days.", None),
    "pricedrops": (
        count_recent_pricedrops, recent_pricedrops, "Sales / Price Drops",
        "Items whose price dropped in the last 7 days. Sorted by when the "
        "drop happened.",
        "No price drops in the last 7 days. Try again tomorrow. They show "
        "up most days."),
}


@bp.route("/instock/<kind>", strict_slashes=False)
def instock(kind):
    """Full page for a recent slice (new / missed / popular / pricedrops).

    Doubles as a legacy-URL bridge: the pre-2026-06 Perl site used
    /instock/<part-type>[/] category pages. A <kind> that's a known part type
    (resolved through type aliases) 301s to its canonical /browse?type=<type>
    so Google's existing index + inbound links transfer instead of 404ing.
    strict_slashes=False so the legacy trailing-slash form matches too."""
    cfg = _RECENT_KINDS.get(kind)
    if cfg is None:
        canon = canonical_type(kind)
        if canon in TYPE_LABELS:
            return redirect("/browse?type=" + canon, code=301)
        abort(404)
    count_fn, page_fn, title, blurb, empty = cfg
    return _recent_route(count_fn, page_fn, kind, title,
                         blurb=blurb, empty=empty)


@bp.route("/instock/<kind>/parts")
def instock_parts(kind):
    """htmx fragment for filter / pagination changes on a recent page —
    the /instock analogue of /browse/parts. Returns the grid (innerHTML
    target #parts-grid) + chips + pagination (OOB) in one round-trip.
    Non-htmx hits (refresh / share / new tab) redirect to the canonical
    /instock/<kind>?... full page so they get the chrome, not raw HTML."""
    cfg = _RECENT_KINDS.get(kind)
    if cfg is None:
        abort(404)
    count_fn, page_fn, title, blurb, empty = cfg
    f = _parse_filters(request)
    if not request.headers.get("HX-Request"):
        return redirect(_recent_canonical_url(kind, f))
    parts, total, blurb = _recent_data(kind, count_fn, page_fn, f, blurb)
    _decorate_recent(parts)
    rendered = render_template(
        "partials/_browse_results.html",
        **_browse_context(f, parts, total,
                          companies_list=recent_companies(kind)),
        page_kind=kind, page_title=title,
        page_blurb=blurb, empty_blurb=empty)
    resp = make_response(rendered)
    resp.headers["HX-Push-Url"] = _recent_canonical_url(kind, f)
    return resp


@bp.route("/browse/parts")
def browse_parts():
    """htmx fragment for filter / pagination changes on /browse.

    Returns the cards+table grid as the main response (innerHTML
    swap target = #parts-grid) PLUS the chip strip + pagination
    controls as hx-swap-oob fragments so all three update from one
    round-trip. See partials/_browse_results.html.

    Direct (non-htmx) access — refreshes, shared links, paste-into-
    new-tab — get a 302 to the canonical /browse?... URL. Without
    this redirect the user lands on unstyled raw fragment HTML (no
    base.html chrome, no Tailwind, no header)."""
    f = _parse_filters(request)
    if not request.headers.get("HX-Request"):
        return redirect(_browse_canonical_url(f))
    total = count_in_stock(
        type_=f["sel_type"], companies_=f["companies_"],
        excludes_=f["excludes_"],
        q=f["q"], price_min=f["price_min"],
        price_max=f["price_max"])
    _clamp_page(f, total)
    parts = in_stock(
        type_=f["sel_type"], companies_=f["companies_"],
        excludes_=f["excludes_"],
        q=f["q"], price_min=f["price_min"],
        price_max=f["price_max"], sort=f["sort"],
        page=f["page"])
    _enrich_for_browse(parts)
    rendered = render_template(
        "partials/_browse_results.html",
        **_browse_context(f, parts, total))
    resp = make_response(rendered)
    # Tell htmx to put /browse?... in the address bar, NOT
    # /browse/parts?... — so refresh / share / new-tab all land on
    # the full page, not the fragment. Overrides hx-push-url="true"
    # in the form / pagination links.
    resp.headers["HX-Push-Url"] = _browse_canonical_url(f)
    return resp
