// E1 (Phase E — olam-repos-and-runbooks): read ~/.olam/config.json and
// expose it to the host-CP API endpoints (/api/repos, /api/runbooks).
//
// Never crashes: missing file → empty arrays, corrupt JSON → { error }.
// Mirrors the workspace-catalog.mjs pattern: pure function, env-driven
// path, no side effects at module load time.

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

const DEFAULT_CONFIG_PATH =
  process.env.OLAM_CONFIG_PATH ??
  path.join(os.homedir(), '.olam', 'config.json');

/**
 * @typedef {object} RepoEntry
 * @property {string} name
 * @property {string} path
 * @property {string} [description]
 * @property {number} [addedAt]
 * @property {number} [updatedAt]
 */

/**
 * @typedef {object} Runbook
 * @property {string} name
 * @property {string[]} repos
 * @property {number} [updatedAt]
 * @property {Record<string, Record<string, number>>} [portMap]
 * @property {Record<string, Record<string, string>>} [env]
 */

/**
 * @typedef {{ repos: RepoEntry[], runbooks: Runbook[] }} GlobalConfig
 * @typedef {{ error: string }} ConfigError
 */

/**
 * Load the global olam config from disk.
 * - Missing file → `{ repos: [], runbooks: [] }`
 * - Corrupt JSON → `{ error: string }`
 * - Success → `{ repos: RepoEntry[], runbooks: Runbook[] }`
 *
 * @param {string} [configPath]
 * @returns {GlobalConfig | ConfigError}
 */
export function loadGlobalConfig(configPath = DEFAULT_CONFIG_PATH) {
  if (!fs.existsSync(configPath)) {
    return { repos: [], runbooks: [] };
  }
  let raw;
  try {
    raw = fs.readFileSync(configPath, 'utf-8');
  } catch (err) {
    return { error: `Failed to read ${configPath}: ${err.message}` };
  }
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch (err) {
    return { error: `Invalid JSON in ${configPath}: ${err.message}` };
  }
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    return { error: `${configPath} does not contain a JSON object` };
  }
  return {
    repos: Array.isArray(parsed.repos) ? parsed.repos : [],
    runbooks: Array.isArray(parsed.runbooks) ? parsed.runbooks : [],
  };
}
