// config/version-defaults.ts — Central registry loader for default-versions.json
// All hardcoded versions in the codebase are sourced from this file.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import type { VersionDefaults } from '../types/infrastructure.js';

const FALLBACK: VersionDefaults = {
  docker: {},
  terraform: {},
  npm: {},
  jvm: {},
  scala: {},
  elixir: {},
  dart: {},
  rust: {},
  cdn: {},
  standards: {},
};

function loadDefaults(): VersionDefaults {
  try {
    const dir = dirname(fileURLToPath(import.meta.url));
    const raw = readFileSync(join(dir, 'default-versions.json'), 'utf-8');
    return JSON.parse(raw) as VersionDefaults;
  } catch {
    return FALLBACK;
  }
}

const defaults: VersionDefaults = loadDefaults();

export function getDockerTag(service: string): string {
  return defaults.docker[service]?.tag ?? 'latest';
}

export function getTerraformVersion(resource: string): string {
  return defaults.terraform[resource]?.version ?? '';
}

export function getNpmVersion(pkg: string): string {
  return defaults.npm[pkg]?.version ?? 'latest';
}

export function getJvmVersion(lib: string): string {
  return defaults.jvm[lib]?.version ?? '';
}

export function getScalaVersion(tool: string): string {
  return defaults.scala[tool]?.version ?? '';
}

export function getElixirVersion(dep: string): string {
  return defaults.elixir[dep]?.version ?? '';
}

export function getDartVersion(pkg: string): string {
  return defaults.dart[pkg]?.version ?? '';
}

export function getRustVersion(crate: string): string {
  return defaults.rust[crate]?.version ?? '';
}

export function getCdnUrl(name: string): string {
  const entry = defaults.cdn[name];
  if (!entry) {
    return '';
  }
  return entry.baseUrl.replace('{version}', entry.version);
}

export function getStandardVersion(name: string): string {
  return defaults.standards?.[name]?.version ?? '';
}
