import { usePowerQuery } from './use-power-query';
import { fetchJson } from '../lib/api';
import { POLL_INTERVALS } from '../lib/constants';

export interface StatsResponse {
  context: {
    project: {
      id: string;
      name: string;
      root: string;
      manifest_state: 'present' | 'missing' | 'invalid';
    };
    grove: {
      id: string | null;
      name: string | null;
      slug: string | null;
      mode: 'local' | null;
      binding_id: string | null;
      connection_state: 'local-only' | 'pending' | 'legacy';
    };
    request: {
      source: string;
      project_id: string;
      grove_id: string | null;
      machine_id: string;
      session_id: string | null;
    };
  };
  daemon: {
    pid: number;
    port: number;
    version: string;
    version_label?: string;
    uptime_seconds: number;
    active_sessions: string[];
    runtime?: { source: 'stable' | 'dev' | 'beta'; command: string | null };
  };
  vault: {
    path: string;
    name: string;
    session_count: number;
    batch_count: number;
    spore_count: number;
    plan_count: number;
    artifact_count: number;
    entity_count: number;
    edge_count: number;
  };
  embedding: {
    provider: string;
    model: string;
    queue_depth: number;
    embedded_count: number;
    total_embeddable: number;
  };
  agent: {
    last_run_at: number | null;
    last_run_status: string | null;
    total_runs: number;
  };
  digest: {
    freshest_tier: number | null;
    generated_at: number | null;
    tiers_available: number[];
  };
  canopy: {
    entries_count: number;
    described_count: number;
  };
  unprocessed_batches: number;
}

export function useDaemon() {
  return usePowerQuery<StatsResponse>({
    queryKey: ['daemon-stats'],
    queryFn: ({ signal }) => fetchJson<StatsResponse>('/stats', { signal }),
    refetchInterval: POLL_INTERVALS.STATS,
    pollCategory: 'standard',
  });
}
