"""Server-rendered SVG sparklines.

Why SVG and not Chart.js for these: there are many per page (one per
build line / browse card), and each is small. Server-side SVG costs
~hundreds of bytes per chart, is crawler-visible, and survives htmx
swaps without any JS re-init. Chart.js handles the bigger one-per-
page interactive chart at the bottom of the build page (price-history
of the whole build over time) where the cost/benefit flips.

`sparkline_svg(points, window_start=...)` is the at-a-glance form
used by /browse cards + /build line items. It locks the X axis to
a fixed date span [window_start, today] so all sparklines on the
page are temporally comparable regardless of how much actual history
each part has — without that, a part with 10 years of history and
one with 1 week look identical in width while meaning radically
different things.

Visual rendering with a window:
  - From window_start to the FIRST in-window observation:
    **dotted** flat at that observation's price. Signals "we don't
    have data for this period." When the first observation is at
    window_start itself, this segment is zero-length and invisible.
  - From the first observation through subsequent in-window
    observations and onward to today (extending at the last
    observed price): **solid**.
  - No decorative end-dot. Clean visual.
  - Color: green if last < first (price trended down — good for
    buyer), red if last > first, gray if flat.
  - 0 in-window points → empty string (no SVG).
"""

from datetime import date as _date, datetime as _datetime


_DOWN = "#059669"   # emerald-600 — price dropped (good for buyer)
_UP   = "#dc2626"   # red-600     — price rose
_FLAT = "#9ca3af"   # gray-400    — flat


def _as_date(v):
    """Coerce a date-or-datetime to a date. DB rows give us datetime
    (TIMESTAMP column); synthetic / test callers may pass plain
    date. Tolerate both."""
    if isinstance(v, _datetime):
        return v.date()
    return v


def sparkline_svg(points, window_start=None, today=None,
                  width=84, height=22, padding=2) -> str:
    """Render an inline SVG sparkline.

    `points` is an iterable of dicts with at least `price` and
    `updated` keys (the shape returned by
    queries.price_history_for_ids). Order doesn't matter — we
    re-sort here.

    With `window_start` (a date) the X axis is locked to
    [window_start, today]. Points outside the window are ignored.
    See module docstring for the dotted-leading + solid-trailing
    rendering rules.

    Without `window_start`, the function falls back to the legacy
    behavior: x-axis spans first-to-last observation by index.
    Kept for any caller that hasn't migrated to the windowed form
    (none in-tree as of this rewrite).
    """
    if not points:
        return ""

    if today is None:
        today = _date.today()

    sorted_pts = sorted(points, key=lambda p: p["updated"])

    # Window-mode (the new at-a-glance form)
    if window_start is not None:
        in_window = [p for p in sorted_pts
                     if _as_date(p["updated"]) >= window_start]
        if not in_window:
            return ""
        return _render_windowed(in_window, window_start, today,
                                width, height, padding)

    # Legacy fallback: index-based positioning, no dashed prefix
    return _render_legacy(sorted_pts, width, height, padding)


# --------------------------------------------------------------------------- #
# windowed renderer (the form site-ng actually uses)
# --------------------------------------------------------------------------- #
def _render_windowed(in_window, window_start, today,
                     width, height, padding) -> str:
    inner_w = width - 2 * padding
    inner_h = height - 2 * padding
    span_days = (today - window_start).days or 1

    def x_at(d):
        return padding + ((d - window_start).days / span_days) * inner_w

    prices = [float(p["price"]) for p in in_window]
    lo, hi = min(prices), max(prices)
    rng = hi - lo or 1.0

    def y_at(price):
        return padding + (1 - (price - lo) / rng) * inner_h

    color = _FLAT
    if prices[-1] < prices[0]:
        color = _DOWN
    elif prices[-1] > prices[0]:
        color = _UP

    first_pt = in_window[0]
    first_date = first_pt["updated"].date()
    first_y = y_at(float(first_pt["price"]))

    last_pt = in_window[-1]
    last_date = last_pt["updated"].date()
    last_y = y_at(float(last_pt["price"]))

    fragments = [
        f'<svg width="{width}" height="{height}" '
        f'viewBox="0 0 {width} {height}" class="inline-block align-middle">'
    ]

    # Dotted prefix from window_start → first observation, flat at
    # first observation's price. Skipped when first observation is
    # at (or before) window_start.
    if first_date > window_start:
        x0 = x_at(window_start)
        x1 = x_at(first_date)
        fragments.append(
            f'<polyline points="{x0:.1f},{first_y:.1f} '
            f'{x1:.1f},{first_y:.1f}" fill="none" stroke="{color}" '
            f'stroke-width="1.5" stroke-dasharray="2,2"/>')

    # Solid through all in-window observations + a final segment
    # extending to today at the last observed price (assumes the
    # price has been stable since the most recent recorded change —
    # if it had changed, the scanner would have logged a new point).
    solid = [(x_at(_as_date(p["updated"])), y_at(float(p["price"])))
             for p in in_window]
    if last_date < today:
        solid.append((x_at(today), last_y))
    if len(solid) >= 2:
        pts_str = " ".join(f"{x:.1f},{y:.1f}" for x, y in solid)
        fragments.append(
            f'<polyline points="{pts_str}" fill="none" stroke="{color}" '
            f'stroke-width="1.5" stroke-linejoin="round" '
            f'stroke-linecap="round"/>')
    elif solid:
        # Edge case: a single point AT (or just before) today — only
        # one solid coord. Render a tiny dot rather than nothing.
        x, y = solid[0]
        fragments.append(
            f'<circle cx="{x:.1f}" cy="{y:.1f}" r="1.5" fill="{color}"/>')

    fragments.append("</svg>")
    return "".join(fragments)


# --------------------------------------------------------------------------- #
# legacy fallback (no window) — kept for safety, not used in-tree
# --------------------------------------------------------------------------- #
def _render_legacy(sorted_pts, width, height, padding) -> str:
    n = len(sorted_pts)
    inner_w = width - 2 * padding
    inner_h = height - 2 * padding
    prices = [float(p["price"]) for p in sorted_pts]
    lo, hi = min(prices), max(prices)
    rng = hi - lo or 1.0

    def y_at(price):
        return padding + (1 - (price - lo) / rng) * inner_h

    color = _FLAT
    if n >= 2:
        if prices[-1] < prices[0]:
            color = _DOWN
        elif prices[-1] > prices[0]:
            color = _UP

    if n == 1:
        y = y_at(prices[0])
        return (
            f'<svg width="{width}" height="{height}" '
            f'viewBox="0 0 {width} {height}" class="inline-block align-middle">'
            f'<polyline points="{padding},{y:.1f} {width-padding},{y:.1f}" '
            f'fill="none" stroke="{color}" stroke-width="1.5"/>'
            f"</svg>")

    def x_at(i):
        return padding + (i / (n - 1)) * inner_w

    pts_str = " ".join(f"{x_at(i):.1f},{y_at(prices[i]):.1f}"
                       for i in range(n))
    return (
        f'<svg width="{width}" height="{height}" '
        f'viewBox="0 0 {width} {height}" class="inline-block align-middle">'
        f'<polyline points="{pts_str}" fill="none" stroke="{color}" '
        f'stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round"/>'
        f"</svg>")
