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

export function resolveBootstrapRefPath(baseDir: string, ref: string): string {
  return path.isAbsolute(ref)
    ? ref
    : path.resolve(baseDir, ref);
}

export function loadBootstrapJsonValue(
  baseDir: string,
  ref: string,
  label: string,
): unknown {
  const filePath = resolveBootstrapRefPath(baseDir, ref);
  if (!fs.existsSync(filePath)) {
    throw new Error(`${label} not found at ${filePath}`);
  }
  try {
    return JSON.parse(fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, ''));
  } catch (err) {
    throw new Error(`Failed to parse ${label}: ${err instanceof Error ? err.message : String(err)}`);
  }
}

export function loadBootstrapJsonObject(
  baseDir: string,
  ref: string,
  label: string,
): Record<string, unknown> {
  const parsed = loadBootstrapJsonValue(baseDir, ref, label);
  if (!isRecord(parsed)) {
    throw new Error(`${label} must contain a JSON object`);
  }
  return parsed;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
