/**
 * financecalendar.com — kostenloser Wirtschaftskalender, auch für kommerzielle
 * Nutzung freigegeben, Bedingung: ein sichtbarer Link zur Quelle (steht im UI).
 * Hier nur Abruf und Umformung; was gespeichert wird, entscheidet der Service.
 */

const SOURCE = 'https://www.financecalendar.com/wp-json/fc/v1/calendar';
/** Länder, deren Daten Krypto bewegen: USA zuerst, dazu Euroraum, DE, UK, Japan, China, Schweiz. */
export const CALENDAR_COUNTRIES = ['US', 'EU', 'DE', 'GB', 'JP', 'CN', 'CH'] as const;
const TIMEOUT = 15_000;

interface SourceEvent {
  id?: string;
  series_code?: string;
  title?: string;
  name?: string;
  country?: string | null;
  impact?: string | null;
  category?: string | null;
  date?: string;
  release_at_utc?: string | null;
  time_utc?: string | null;
  period?: string | null;
  unit?: string | null;
  consensus?: string | number | null;
  prior?: string | number | null;
  actual?: string | number | null;
  status?: string | null;
  source_url?: string | null;
}

export interface CalendarEventInput {
  id: string;
  seriesCode: string;
  title: string;
  country: string | null;
  impact: string | null;
  category: string | null;
  eventDate: string;
  releaseAt: Date | null;
  period: string | null;
  unit: string | null;
  consensus: string | null;
  prior: string | null;
  actual: string | null;
  status: string | null;
  sourceUrl: string | null;
}

const text = (value: unknown, max: number): string | null => {
  if (typeof value !== 'string' && typeof value !== 'number') return null;
  const trimmed = String(value).trim();
  return trimmed ? trimmed.slice(0, max) : null;
};

/** Ein Quell-Eintrag → unsere Zeile; unvollständige Einträge fallen weg. */
export function toEventInput(event: SourceEvent): CalendarEventInput | null {
  const id = text(event.id, 200);
  const seriesCode = text(event.series_code, 120);
  const title = text(event.title ?? event.name, 500);
  const eventDate = text(event.date, 10);
  if (!id || !seriesCode || !title || !eventDate || !/^\d{4}-\d{2}-\d{2}$/.test(eventDate)) return null;

  let releaseAt: Date | null = null;
  if (event.release_at_utc) {
    const parsed = new Date(event.release_at_utc);
    if (!Number.isNaN(parsed.getTime())) releaseAt = parsed;
  } else if (event.time_utc && /^\d{2}:\d{2}/.test(event.time_utc)) {
    const parsed = new Date(`${eventDate}T${event.time_utc.slice(0, 5)}:00Z`);
    if (!Number.isNaN(parsed.getTime())) releaseAt = parsed;
  }

  return {
    id,
    seriesCode,
    title,
    country: text(event.country, 8),
    impact: text(event.impact, 16),
    category: text(event.category, 80),
    eventDate,
    releaseAt,
    period: text(event.period, 80),
    unit: text(event.unit, 80),
    consensus: text(event.consensus, 80),
    prior: text(event.prior, 80),
    actual: text(event.actual, 80),
    status: text(event.status, 32),
    sourceUrl: text(event.source_url, 2000),
  };
}

/** Termine hoher und mittlerer Wichtigkeit im Zeitraum (max. 92 Tage je Abruf). */
export async function fetchCalendar(from: string, to: string): Promise<CalendarEventInput[]> {
  const query = new URLSearchParams({ from, to, country: CALENDAR_COUNTRIES.join(','), impact: 'high,medium', tz: 'UTC' });
  const response = await fetch(`${SOURCE}?${query}`, { signal: AbortSignal.timeout(TIMEOUT) });
  if (!response.ok) throw new Error(`financecalendar.com returned ${response.status}`);
  const body = (await response.json()) as { events?: SourceEvent[] };
  return (body.events ?? []).map(toEventInput).filter((event): event is CalendarEventInput => event !== null);
}
