"""Public product detail page — /p/<id>/<slug>.

An indexable, shareable page per product: the price-history chart, the
key facts, and a prominent "View at retailer" button. It is a COMPLEMENT
to the buy path, never in front of it — the listing title still links
straight out to the retailer (see memory: no-friction-to-buy-click). This
page is reached from the card's "Price history & details" affordance.

Identity is the numeric parts.id (same id our /jump links use); the slug
is cosmetic/SEO and any non-canonical slug 301-redirects to the canonical
one, so old/share links converge for SEO. Built in shared ngsite so the
sister sites (e.g. onlineammofinder) get it too.
"""

from __future__ import annotations

import json
from datetime import date

from flask import Blueprint, abort, current_app, redirect, render_template

from ..product_url import product_slug
from ..product_match import SAFE_TYPES, find_matches
from ..queries import part_detail, price_history_capped, same_type_pool

bp = Blueprint("product", __name__)

# Chart point cap. Real products top out around ~650 recorded changes, so this
# never truncates a genuine product — it's a safety valve so a pathological row
# (e.g. the empty-url collision sentinel with ~1M points) can't blow up the
# page. Tweakable: raise/lower freely; the "(most recent N)" note only shows
# when a product actually exceeds it.
MAX_POINTS = 2000


def _series_and_stats(part):
    """Build the Chart.js series [{date, price}] of actual price TRANSITIONS
    plus a stats dict. price_history carries a row per legacy scan (the old
    Perl scanner logged every scan, not just on change), so we collapse
    consecutive identical prices to the points where the price actually
    changed — that makes the chart the true step function and the count mean
    real changes, not rows. A final point at today's current price runs the
    line to now. Returns (series, stats)."""
    points, _total_raw, first = price_history_capped(part["id"], MAX_POINTS)
    deduped = []
    for p in points:
        pr = round(float(p["price"]), 2)
        if not deduped or deduped[-1]["price"] != pr:        # keep transitions only
            deduped.append({"date": p["updated"].strftime("%Y-%m-%d"), "price": pr})
    changes = max(0, len(deduped) - 1)                       # # of actual price changes
    cur_price = round(float(part["price"]), 2)
    today = date.today().strftime("%Y-%m-%d")
    series = list(deduped)
    if series and series[-1]["date"] != today:               # hold flat to today
        series.append({"date": today, "price": cur_price})
    elif not series:
        series = [{"date": today, "price": cur_price}]
    prices = [s["price"] for s in series]
    stats = {
        "low": min(prices),
        "high": max(prices),
        "current": cur_price,
        "changes": changes,
        "first_seen": first or part.get("added"),
    }
    return series, stats


@bp.route("/p/<int:part_id>")
@bp.route("/p/<int:part_id>/<slug>")
def detail(part_id, slug=None):
    part = part_detail(part_id)
    if not part:
        abort(404)
    # Blank-description rows are the empty-url collision sentinel / junk, not a
    # real product — don't serve a titleless detail page (and short-circuit
    # before any price_history query touches the pathological id).
    if not (part.get("description") or "").strip():
        abort(404)
    canonical = product_slug(part["description"])
    if slug != canonical:                     # bare or stale slug -> canonical
        return redirect("/p/%d/%s" % (part_id, canonical), code=301)
    series, stats = _series_and_stats(part)
    # Cross-merchant price comparison (v1): find the SAME product at OTHER
    # merchants in our own catalog. Limited to low-variant types (SAFE_TYPES)
    # where the title identifies the item; best-effort so a matching hiccup
    # never breaks the page.
    matches = {"confident": [], "possible": []}
    if part.get("type") in SAFE_TYPES:
        try:
            matches = find_matches(same_type_pool(part["type"]), part)
        except Exception:
            current_app.logger.exception("product_match failed for %s", part_id)
    return render_template(
        "product.html", p=part, stats=stats,
        series_json=json.dumps(series),
        has_chart=len(series) > 1,
        matches=matches,
        match_total=len(matches["confident"]) + len(matches["possible"]))
