import type { PricePoint } from "@/lib/playground/stockTradingEnv";

type AlphaVantageDailyResponse = {
  "Time Series (Daily)"?: Record<
    string,
    {
      "4. close"?: string;
    }
  >;
  "Error Message"?: string;
  Note?: string;
};

export function alphaVantageDailyToPoints(json: unknown): { points: PricePoint[]; error?: string } {
  const data = json as AlphaVantageDailyResponse;
  if (data?.["Error Message"]) return { points: [], error: data["Error Message"] };
  if (data?.Note) return { points: [], error: data.Note };

  const ts = data?.["Time Series (Daily)"];
  if (!ts) return { points: [], error: "Alpha Vantage: missing Time Series (Daily)" };

  const points: PricePoint[] = [];
  for (const [dateStr, row] of Object.entries(ts)) {
    const closeStr = row?.["4. close"];
    const close = closeStr ? Number(closeStr) : NaN;
    const t = Math.floor(Date.parse(`${dateStr}T00:00:00Z`) / 1000);
    if (Number.isFinite(t) && Number.isFinite(close) && close > 0) points.push({ t, close });
  }

  points.sort((a, b) => a.t - b.t);
  return { points };
}

export function resampleWeekly(points: PricePoint[]): PricePoint[] {
  // Keep last close per ISO week (approx).
  const byWeek = new Map<string, PricePoint>();
  for (const p of points) {
    const d = new Date(p.t * 1000);
    const year = d.getUTCFullYear();
    const jan1 = new Date(Date.UTC(year, 0, 1));
    const dayOfYear = Math.floor((d.getTime() - jan1.getTime()) / 86400000) + 1;
    const week = Math.ceil(dayOfYear / 7);
    const key = `${year}-W${week}`;
    const prev = byWeek.get(key);
    if (!prev || p.t > prev.t) byWeek.set(key, p);
  }
  return Array.from(byWeek.values()).sort((a, b) => a.t - b.t);
}

export function clipToRange(points: PricePoint[], range: "6mo" | "1y" | "2y" | "5y"): PricePoint[] {
  const tradingDays =
    range === "6mo" ? 126 : range === "1y" ? 252 : range === "2y" ? 504 : 1260;
  if (points.length <= tradingDays) return points;
  return points.slice(points.length - tradingDays);
}

