import { fetchJson } from "@/lib/api";
import { API_ENDPOINTS, STATUS_POLL_ACTIVE_MS, STATUS_POLL_IDLE_MS } from "@/lib/constants";
import { usePowerQuery } from "@oak/ui/hooks/use-power-query";

export interface IndexStats {
    files_indexed: number;
    chunks_indexed: number;
    memories_stored: number;
    memories_unembedded: number;
    last_indexed: string | null;
    duration_seconds: number;
    status: string;
    progress: number;
    total: number;
    ast_stats?: {
        ast_success: number;
        ast_fallback: number;
        line_based: number;
    };
}

export interface EmbeddingStats {
    providers: string[];
    total_embeds: number;
}

export interface SummarizationStatus {
    enabled: boolean;
    provider: string | null;
    model: string | null;
}

export interface StorageStats {
    sqlite_size_bytes: number;
    chromadb_size_bytes: number;
    sqlite_size_mb: string;
    chromadb_size_mb: string;
    total_size_mb: string;
}

export interface BackupSummary {
    exists: boolean;
    last_backup: string | null;
    age_hours: number | null;
    size_bytes?: number;
}

export interface VersionInfo {
    running: string;
    installed: string | null;
    update_available: boolean;
}

export interface UpgradeInfo {
    needed: boolean;
    config_version_outdated: boolean;
    pending_migrations: number;
}

export interface TeamStatus {
    configured: boolean;
    connected: boolean;
    members_online: number;
}

export interface CloudRelayStatus {
    connected: boolean;
    worker_url: string | null;
    mcp_endpoint: string | null;
    custom_domain: string | null;
    worker_name: string | null;
}

export interface DaemonStatus {
    status: string;
    machine_id: string | null;
    cli_command: string;
    indexing: boolean;
    embedding_provider: string | null;
    embedding_stats: EmbeddingStats | null;
    summarization: SummarizationStatus;
    uptime_seconds: number;
    project_root: string;
    index_stats: IndexStats;
    file_watcher: {
        enabled: boolean;
        running: boolean;
        pending_changes: number;
    };
    storage: StorageStats;
    backup: BackupSummary;
    version: VersionInfo;
    upgrade: UpgradeInfo;
    team?: TeamStatus;
    cloud_relay?: CloudRelayStatus;
}

export function useStatus() {
    return usePowerQuery<DaemonStatus>({
        queryKey: ["status"],
        queryFn: ({ signal }: { signal: AbortSignal }) => fetchJson(API_ENDPOINTS.STATUS, { signal }),
        refetchInterval: (query) => {
            const data = query.state.data;
            if (!data) return STATUS_POLL_ACTIVE_MS;
            const isActive = data.indexing || data.file_watcher?.pending_changes > 0;
            return isActive ? STATUS_POLL_ACTIVE_MS : STATUS_POLL_IDLE_MS;
        },
        pollCategory: "heartbeat",
    });
}
