// 시스템 상태 store — Phase B에서 신규.
// /dashboard/ API 응답을 60초 주기로 폴링하고, 첫 subscribe 시 자동 시작한다.
// SystemStatusDot(B)과 dashboard(C)가 같은 fetch를 공유해 중복 호출을 방지.
//
// API 응답 shape: app/api/dashboard.py DashboardResponse 참조

import { writable } from 'svelte/store';
import { api } from '$lib/api';

export interface DomainCount {
  domain: string | null;
  count: number;
}

export interface RecentDocument {
  id: number;
  title: string | null;
  file_format: string;
  ai_domain: string | null;
  created_at: string;
}

export interface PipelineStatus {
  stage: string;
  status: string;
  count: number;
}

export interface QueueLag {
  stage: string;
  pending: number;
  processing: number;
  failed: number;
  oldest_pending_age_sec: number | null;
}

export interface TierHealthStack {
  triage_total: number;
  escalated_total: number;
  escalation_by_reason: Record<string, number>;
  escalation_by_domain: Record<string, number>;
  triage_json_invalid: number;
  suppressed_total: number;
  // Day 4 신규 — deep_summary 호출 안정성
  deep_total?: number;
  deep_err_total?: number;
}

export interface DashboardSummary {
  today_added: number;
  today_by_domain: DomainCount[];
  inbox_count: number;
  law_alerts: number;
  recent_documents: RecentDocument[];
  pipeline_status: PipelineStatus[];
  failed_count: number;
  total_documents: number;
  documents_count: number;
  memos_count: number;
  news_count: number;
  // §4 — category 카드 + 승인 pending + queue lag
  category_counts: Record<string, number>;
  library_pending_suggestions: number;
  queue_lag: QueueLag[];
  // B-3 — tier 관측성 3종 카드
  tier_health?: TierHealthStack;
}

const POLL_INTERVAL_MS = 60_000;

let pollHandle: ReturnType<typeof setInterval> | null = null;
let subscriberCount = 0;
let inFlight: Promise<void> | null = null;

const internal = writable<DashboardSummary | null>(null, (_set) => {
  // svelte writable의 두 번째 인자는 첫 구독 시 호출되는 start fn,
  // 반환값은 마지막 unsubscribe 시 호출되는 stop fn.
  subscriberCount += 1;
  if (subscriberCount === 1) {
    void refresh();
    pollHandle = setInterval(() => void refresh(), POLL_INTERVAL_MS);
  }
  return () => {
    subscriberCount -= 1;
    if (subscriberCount === 0 && pollHandle) {
      clearInterval(pollHandle);
      pollHandle = null;
    }
  };
});

export const dashboardSummary = { subscribe: internal.subscribe };

export async function refresh(): Promise<void> {
  // 동시 fetch 합치기 — 폴링 + 수동 새로고침이 겹쳐도 1회만
  if (inFlight) return inFlight;
  inFlight = (async () => {
    try {
      const data = await api<DashboardSummary>('/dashboard/');
      internal.set(data);
    } catch (err) {
      console.error('대시보드 폴링 실패:', err);
    } finally {
      inFlight = null;
    }
  })();
  return inFlight;
}
