export interface StoredMlbSnapshot {
  captured_at: string;
  phase_score: number | null;
  probable_starters: {
    home: any | null;
    away: any | null;
  };
  lineups: any | null;
  travel: any | null;
  weather: any | null;
  weather_run_bias: number | null;
  bullpen: {
    home: any | null;
    away: any | null;
  };
  application_hints: any | null;
}

export interface MlbOperationalAlert {
  code: 'missing_probable_starters' | 'missing_lineups_near_first_pitch' | 'zero_candidate_prop_game' | 'missing_mlb_prop_feed';
  severity: 'warning' | 'critical';
  message: string;
}

function minutesToFirstPitch(startsAt: string): number | null {
  const ts = new Date(startsAt).getTime();
  if (!Number.isFinite(ts)) return null;
  return Math.round((ts - Date.now()) / 60000);
}

export function buildStoredMlbSnapshotFromPhase(phase: any, capturedAt: string = new Date().toISOString()): StoredMlbSnapshot {
  const raw = phase?.rawData || {};

  return {
    captured_at: capturedAt,
    phase_score: phase?.score ?? null,
    probable_starters: {
      home: raw.firstFive?.homeStarter || null,
      away: raw.firstFive?.awayStarter || null,
    },
    lineups: raw.context?.lineups || null,
    travel: raw.context?.travel || null,
    weather: raw.context?.weather || null,
    weather_run_bias: raw.context?.weatherRunBias ?? null,
    bullpen: {
      home: raw.bullpen?.homeBullpen?.workload || null,
      away: raw.bullpen?.awayBullpen?.workload || null,
    },
    application_hints: raw.applicationHints || null,
  };
}

export function summarizeMlbOperationalAlerts(params: {
  snapshot: StoredMlbSnapshot | null;
  startsAt: string;
  candidateCount?: number | null;
  feedRowCount?: number | null;
  teamName?: string;
}): MlbOperationalAlert[] {
  const alerts: MlbOperationalAlert[] = [];
  const snapshot = params.snapshot;

  if (!snapshot) return alerts;

  const homeStarter = snapshot.probable_starters?.home?.name || null;
  const awayStarter = snapshot.probable_starters?.away?.name || null;
  if (!homeStarter || !awayStarter) {
    alerts.push({
      code: 'missing_probable_starters',
      severity: 'critical',
      message: 'Probable starters are missing for this MLB game.',
    });
  }

  const mins = minutesToFirstPitch(params.startsAt);
  const homeConfirmed = String(snapshot.lineups?.homeStatus || '').toLowerCase().includes('confirmed');
  const awayConfirmed = String(snapshot.lineups?.awayStatus || '').toLowerCase().includes('confirmed');
  if (mins != null && mins <= 120 && (!homeConfirmed || !awayConfirmed)) {
    alerts.push({
      code: 'missing_lineups_near_first_pitch',
      severity: 'warning',
      message: 'Confirmed MLB lineups are still missing within 2 hours of first pitch.',
    });
  }

  if (params.feedRowCount === 0) {
    alerts.push({
      code: 'missing_mlb_prop_feed',
      severity: 'critical',
      message: `${params.teamName || 'MLB team'} has no raw prop feed rows for this game window.`,
    });
  }

  if (params.candidateCount === 0) {
    alerts.push({
      code: 'zero_candidate_prop_game',
      severity: 'warning',
      message: `${params.teamName || 'MLB team'} has zero direct prop candidates.`,
    });
  }

  return alerts;
}
