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>;
};

function getConfigPath(): string {
  return path.join(
    process.env.DATA_DIR ? path.resolve(process.cwd(), process.env.DATA_DIR) : process.cwd(),
    'data',
    'config.json',
  );
}

let cached: ConfigModelProvider[] | null = null;

export function getProviderById(id: string): ConfigModelProvider | undefined {
  if (cached === null) {
    const p = getConfigPath();
    if (!fs.existsSync(p)) {
      cached = [];
      return undefined;
    }
    try {
      const raw = JSON.parse(fs.readFileSync(p, 'utf-8'));
      cached = raw.modelProviders ?? [];
    } catch {
      cached = [];
    }
  }
  return cached?.find((x) => x.id === id);
}
