// src/lib/content/stats-logic.ts — pure helpers for /content/stats (no DB, no IO).

/** Impression-weighted average position; null when there are no impressions. */
export function weightedPosition(
  rows: { position: number | null; impressions: number }[],
): number | null {
  let weight = 0;
  let sum = 0;
  for (const r of rows) {
    if (r.position == null || r.impressions <= 0) continue;
    sum += r.position * r.impressions;
    weight += r.impressions;
  }
  return weight > 0 ? Math.round((sum / weight) * 10) / 10 : null;
}

/** Lowercase scheme+host, strip trailing slash; path/query case preserved. */
export function normalizeUrl(raw: string): string {
  const trimmed = raw.trim();
  try {
    const u = new URL(trimmed);
    const path = u.pathname.replace(/\/+$/, "");
    return `${u.protocol}//${u.host}${path}${u.search}`;
  } catch {
    return trimmed;
  }
}

const POSITION_DROP = 3;
const CLICKS_DROP_RATIO = 0.5;
const CLICKS_FLOOR = 5;

type PeriodMetrics = {
  clicks: number;
  impressions: number;
  position: number | null;
};

/** F4 décrochage: needs impressions on BOTH periods; then position +3 or clicks -50% (floor 5). */
export function detectDrop(cur: PeriodMetrics, prev: PeriodMetrics): boolean {
  if (cur.impressions <= 0 || prev.impressions <= 0) return false;
  if (
    cur.position != null &&
    prev.position != null &&
    cur.position - prev.position >= POSITION_DROP
  ) {
    return true;
  }
  return (
    prev.clicks >= CLICKS_FLOOR &&
    cur.clicks <= prev.clicks * (1 - CLICKS_DROP_RATIO)
  );
}

/** Daily clicks aligned on [start, end] inclusive; missing days = 0. */
export function densifySeries(
  points: { date: string; clicks: number }[],
  start: string,
  end: string,
): number[] {
  const byDate = new Map(points.map((p) => [p.date, p.clicks]));
  const out: number[] = [];
  const d = new Date(`${start}T00:00:00Z`);
  const stop = new Date(`${end}T00:00:00Z`);
  while (d <= stop) {
    out.push(byDate.get(d.toISOString().slice(0, 10)) ?? 0);
    d.setUTCDate(d.getUTCDate() + 1);
  }
  return out;
}
