/**
 * vMultiProvider local provider registry loader (coder-side).
 *
 * Reads the shared `/data/llama-providers.json` (or `LLAMA_PROVIDERS_PATH`) at
 * startup and caches the parsed result. When the file is absent or invalid,
 * synthesizes a single legacy provider from `LLAMA_SWAP_URL` so both apps
 * start with only legacy env vars (D-1).
 *
 * Schema and pure helpers live in @boocode/contracts/llama-providers.
 * File I/O stays app-local per D-1.
 */
import { readFileSync } from 'node:fs';
import {
  LlamaProvidersFileSchema,
  type LlamaProvidersFile,
  type LlamaProvider,
  type ParsedModelRef,
  parseModelRef as parseModelRefBase,
  formatModelRef,
} from '@boocode/contracts/llama-providers';

export type { LlamaProvidersFile, LlamaProvider, ParsedModelRef };
export { formatModelRef };

/** Synthesize a single legacy provider from env vars. */
function buildLegacyProvider(llamaSwapUrl: string): LlamaProvidersFile {
  return {
    defaultProvider: 'llama-swap',
    providers: [
      {
        id: 'llama-swap',
        label: 'llama-swap',
        baseUrl: llamaSwapUrl,
        kind: 'llama-swap',
      },
    ],
  };
}

let cached: LlamaProvidersFile | null = null;

/**
 * Load (or re-load) the local provider config. Never throws on bad input —
 * falls back to the legacy single-provider shape.
 */
export function loadLlamaProviders(
  providersPath: string | undefined,
  llamaSwapUrl: string,
): LlamaProvidersFile {
  if (!providersPath) {
    cached = buildLegacyProvider(llamaSwapUrl);
    return cached;
  }

  let raw: string;
  try {
    raw = readFileSync(providersPath, 'utf8');
  } catch {
    console.warn(
      `llama-providers: file not found at ${providersPath} — falling back to legacy single-provider`,
    );
    cached = buildLegacyProvider(llamaSwapUrl);
    return cached;
  }

  let json: unknown;
  try {
    json = JSON.parse(raw);
  } catch (err) {
    console.error(
      `llama-providers: invalid JSON in ${providersPath} — falling back to legacy single-provider`,
      err,
    );
    cached = buildLegacyProvider(llamaSwapUrl);
    return cached;
  }

  const parsed = LlamaProvidersFileSchema.safeParse(json);
  if (!parsed.success) {
    console.error(
      `llama-providers: schema validation failed for ${providersPath} — falling back to legacy single-provider`,
      parsed.error.flatten(),
    );
    cached = buildLegacyProvider(llamaSwapUrl);
    return cached;
  }

  cached = parsed.data;
  return cached;
}

/** The cached provider config. Returns legacy fallback if nothing loaded yet. */
export function getLlamaProviders(): LlamaProvidersFile {
  return cached ?? buildLegacyProvider('http://localhost:8080');
}

/**
 * Convenience: parse a model ref against the cached default provider.
 */
export function parseModelRef(ref: string): ParsedModelRef {
  return parseModelRefBase(ref, getLlamaProviders().defaultProvider);
}
