import path from 'node:path';
import fs from 'node:fs';

export type ConfigModelProvider = {
  id: string;
  name: string;
  type: string;
  chatModels: { key: string; name: string }[];
  config: Record<string, unknown>;
};

export type Config = {
  modelProviders: ConfigModelProvider[];
};

const configPath = path.join(
  process.env.DATA_DIR ? path.resolve(process.cwd(), process.env.DATA_DIR) : process.cwd(),
  'data',
  'config.json',
);

let cached: Config | null = null;

export function loadConfig(): Config {
  if (cached) return cached;
  if (!fs.existsSync(configPath)) {
    cached = { modelProviders: [] };
    return cached;
  }
  try {
    const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
    cached = {
      modelProviders: raw.modelProviders ?? [],
    };
    return cached;
  } catch {
    cached = { modelProviders: [] };
    return cached;
  }
}

export function getProviderById(id: string): ConfigModelProvider | undefined {
  return loadConfig().modelProviders.find((p) => p.id === id);
}
