import { api, type HermesTelemetrySnapshot, type HermesWatchdogAlert } from '@/lib/api';
import type { HermesInstanceId, HermesInstanceFilter } from '@/lib/hermes';

export type HermesTelemetryState = Record<HermesInstanceId, HermesTelemetrySnapshot | null>;

export const emptyTelemetryState: HermesTelemetryState = { vijay: null, bheem: null };

export async function loadAllHermesTelemetry(): Promise<HermesTelemetryState> {
  const [vijay, bheem] = await Promise.all([
    api.getHermesTelemetry('vijay'),
    api.getHermesTelemetry('bheem'),
  ]);
  return { vijay, bheem };
}

export function telemetryForFilter(
  telemetry: HermesTelemetryState,
  selectedInstance: HermesInstanceFilter,
): HermesTelemetrySnapshot[] {
  if (selectedInstance === 'all') return [telemetry.vijay, telemetry.bheem].filter(Boolean) as HermesTelemetrySnapshot[];
  return telemetry[selectedInstance] ? [telemetry[selectedInstance]] : [];
}

export function collectWatchdogAlerts(
  telemetry: HermesTelemetryState,
  selectedInstance: HermesInstanceFilter,
): Array<HermesWatchdogAlert & { instanceId: HermesInstanceId }> {
  return telemetryForFilter(telemetry, selectedInstance)
    .flatMap((snapshot) => snapshot.watchdog.alerts.map((alert) => ({ ...alert, instanceId: snapshot.instanceId })))
    .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
}

export function collectBackupEntries(telemetry: HermesTelemetryState, selectedInstance: HermesInstanceFilter) {
  return telemetryForFilter(telemetry, selectedInstance)
    .flatMap((snapshot) => snapshot.backupHistory.entries.map((entry) => ({ ...entry, instanceId: snapshot.instanceId })))
    .sort((a, b) => new Date(b.committedAt).getTime() - new Date(a.committedAt).getTime());
}

export function collectCronEntries(telemetry: HermesTelemetryState, selectedInstance: HermesInstanceFilter) {
  return telemetryForFilter(telemetry, selectedInstance)
    .flatMap((snapshot) => snapshot.cron.entries.map((entry) => ({ ...entry, instanceId: snapshot.instanceId })));
}

export function collectSessionEntries(telemetry: HermesTelemetryState, selectedInstance: HermesInstanceFilter) {
  return telemetryForFilter(telemetry, selectedInstance)
    .flatMap((snapshot) => snapshot.sessionList.entries.map((entry) => ({ ...entry, instanceId: snapshot.instanceId })))
    .sort((a, b) => new Date(b.updatedAt ?? b.createdAt ?? 0).getTime() - new Date(a.updatedAt ?? a.createdAt ?? 0).getTime());
}

export function collectSessionEvents(telemetry: HermesTelemetryState, selectedInstance: HermesInstanceFilter) {
  return telemetryForFilter(telemetry, selectedInstance)
    .flatMap((snapshot) => snapshot.sessionEvents.entries.map((entry) => ({ ...entry, instanceId: snapshot.instanceId })))
    .sort((a, b) => new Date(b.timestamp ?? 0).getTime() - new Date(a.timestamp ?? 0).getTime());
}
