import type { VesselAnalysisDto } from '../types';

const API_BASE = '/api/kcg';

export interface AnalysisStats {
  total: number;
  critical: number;
  high: number;
  medium: number;
  low: number;
  dark: number;
  spoofing: number;
  clusterCount: number;
  gearGroups: number;
  gearCount: number;
}

export interface VesselAnalysisResponse {
  count: number;
  items: VesselAnalysisDto[];
  stats: AnalysisStats;
}

const EMPTY_STATS: AnalysisStats = {
  total: 0, critical: 0, high: 0, medium: 0, low: 0,
  dark: 0, spoofing: 0, clusterCount: 0, gearGroups: 0, gearCount: 0,
};

export async function fetchVesselAnalysis(): Promise<VesselAnalysisResponse> {
  const res = await fetch(`${API_BASE}/vessel-analysis`, {
    headers: { accept: 'application/json' },
  });
  if (!res.ok) return { count: 0, items: [], stats: EMPTY_STATS };
  const data = await res.json() as VesselAnalysisResponse;
  return {
    count: data.count ?? 0,
    items: data.items ?? [],
    stats: data.stats ?? EMPTY_STATS,
  };
}

export interface FleetCompany {
  id: number;
  nameCn: string;
  nameEn: string;
}

/* ── Group Polygon Types ─────────────────────────────────────── */

export interface MemberInfo {
  mmsi: string;
  name: string;
  lat: number;
  lon: number;
  sog: number;
  cog: number;
  role: string;
  isParent: boolean;
}

export interface GroupPolygonDto {
  groupType: 'FLEET' | 'GEAR_IN_ZONE' | 'GEAR_OUT_ZONE';
  groupKey: string;
  groupLabel: string;
  snapshotTime: string;
  polygon: GeoJSON.Polygon | null;
  centerLat: number;
  centerLon: number;
  areaSqNm: number;
  memberCount: number;
  zoneId: string | null;
  zoneName: string | null;
  members: MemberInfo[];
  color: string;
}

export async function fetchGroupPolygons(): Promise<GroupPolygonDto[]> {
  const res = await fetch(`${API_BASE}/vessel-analysis/groups`, {
    headers: { accept: 'application/json' },
  });
  if (!res.ok) return [];
  const data: { count: number; items: GroupPolygonDto[] } = await res.json();
  return data.items ?? [];
}

export async function fetchGroupDetail(groupKey: string): Promise<GroupPolygonDto | null> {
  const res = await fetch(`${API_BASE}/vessel-analysis/groups/${encodeURIComponent(groupKey)}/detail`);
  if (!res.ok) return null;
  return res.json();
}

export async function fetchGroupHistory(groupKey: string, hours = 24): Promise<GroupPolygonDto[]> {
  const res = await fetch(`${API_BASE}/vessel-analysis/groups/${encodeURIComponent(groupKey)}/history?hours=${hours}`);
  if (!res.ok) return [];
  return res.json();
}

/* ── Gear Correlation Types ──────────────────────────────────── */

export interface GearCorrelationItem {
  targetMmsi: string;
  targetType: 'VESSEL' | 'GEAR_BUOY' | 'GEAR_GROUP';
  targetName: string;
  score: number;
  streak: number;
  observations: number;
  freezeState: string;
  proximityRatio: number | null;
  visitScore: number | null;
  headingCoherence: number | null;
  modelId: number;
  modelName: string;
  isDefault: boolean;
}

export interface GearCorrelationResponse {
  groupKey: string;
  count: number;
  items: GearCorrelationItem[];
}

export async function fetchGroupCorrelations(
  groupKey: string,
  minScore = 0.3,
): Promise<GearCorrelationResponse> {
  const res = await fetch(
    `${API_BASE}/vessel-analysis/groups/${encodeURIComponent(groupKey)}/correlations?minScore=${minScore}`,
    { headers: { accept: 'application/json' } },
  );
  if (!res.ok) return { groupKey, count: 0, items: [] };
  return res.json();
}

/* ── Correlation Tracks (Prediction API) ──────────────────────── */

export interface CorrelationTrackPoint {
  ts: number;   // epoch ms
  lat: number;
  lon: number;
  sog: number;
  cog: number;
}

export interface CorrelationVesselTrack {
  mmsi: string;
  name: string;
  type: string;       // 'VESSEL' | 'GEAR'
  score: number;
  models: Record<string, number>;  // { modelName: score }
  track: CorrelationTrackPoint[];
}

export interface CorrelationTracksResponse {
  groupKey: string;
  vessels: CorrelationVesselTrack[];
}

export async function fetchCorrelationTracks(
  groupKey: string,
  hours = 24,
  minScore = 0.3,
): Promise<CorrelationTracksResponse> {
  const url = `/api/prediction/v1/correlation/${encodeURIComponent(groupKey)}/tracks?hours=${hours}&minScore=${minScore}`;
  console.log('[fetchCorrelationTracks] URL:', url);
  const res = await fetch(url);
  console.log('[fetchCorrelationTracks] status:', res.status, res.statusText);
  if (!res.ok) {
    console.warn('[fetchCorrelationTracks] 실패:', res.status);
    return { groupKey, vessels: [] };
  }
  const data: CorrelationTracksResponse = await res.json();
  console.log('[fetchCorrelationTracks] 응답:', data.vessels.length, '건');
  return data;
}

/* ── Fleet Companies ─────────────────────────────────────────── */

// 캐시 (세션 중 1회 로드)
let companyCache: Map<number, FleetCompany> | null = null;

export async function fetchFleetCompanies(): Promise<Map<number, FleetCompany>> {
  if (companyCache) return companyCache;
  const res = await fetch(`${API_BASE}/fleet-companies`);
  if (!res.ok) return new Map();
  const items: FleetCompany[] = await res.json();
  companyCache = new Map(items.map(c => [c.id, c]));
  return companyCache;
}
