/**
 * Client-side hook for the model registry. Lazy-fetches from
 * `GET /api/public-info/models`, caches in module-level state so
 * multiple components sharing the registry hit the network once per
 * page load. Returns the bundled fallback shape until the network
 * round-trip completes so callers never see `undefined`.
 */

'use client';

import { useEffect, useState } from 'react';
import { KNOWN_MODELS_FALLBACK } from '../agents/known-models';
import type { ModelsRegistry, AgentModels } from './types';

let cached: ModelsRegistry | null = null;
let inflight: Promise<ModelsRegistry> | null = null;

async function load(refresh = false): Promise<ModelsRegistry> {
  if (cached && !refresh) return cached;
  if (inflight && !refresh) return inflight;
  inflight = (async () => {
    try {
      const res = await fetch(`/api/public-info/models${refresh ? '?refresh=1' : ''}`);
      if (res.ok) {
        const data = await res.json();
        cached = data as ModelsRegistry;
        return cached;
      }
    } catch {}
    cached = KNOWN_MODELS_FALLBACK;
    return cached;
  })();
  try { return await inflight; } finally { inflight = null; }
}

export function useModelsRegistry(): {
  registry: ModelsRegistry;
  refresh: () => Promise<void>;
  loading: boolean;
} {
  const [registry, setRegistry] = useState<ModelsRegistry>(cached ?? KNOWN_MODELS_FALLBACK);
  const [loading, setLoading] = useState(!cached);

  useEffect(() => {
    if (cached) return;
    setLoading(true);
    load().then(r => { setRegistry(r); setLoading(false); });
  }, []);

  async function refresh() {
    setLoading(true);
    const r = await load(true);
    setRegistry(r);
    setLoading(false);
  }

  return { registry, refresh, loading };
}

/** Get the model option list for a specific agent CLI type. Returns the
 *  flat list of `[...aliases, ...models]` as the picker expects them. */
export function pickerOptions(registry: ModelsRegistry, cliType: string): string[] {
  const agent: AgentModels | undefined = registry.agents[cliType];
  if (!agent) return ['default'];
  return [...agent.aliases.map(a => a.id), ...agent.models.map(m => m.id)];
}
