import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { parsePolicyPatch } from "./parse.js";
import { resolveGlobalCompactionPolicyPath } from "../paths.js";
import {
  CONFIG_FILE,
  type ICompactionPolicyPatch,
  type IParseResult,
} from "./types.js";

function readConfigFile(configPath: string): IParseResult<ICompactionPolicyPatch> {
  try {
    const raw = readFileSync(configPath, "utf8");
    const json = JSON.parse(raw);
    const parsed = parsePolicyPatch(json);
    if (!parsed.ok) {
      return { ok: false, error: `Invalid ${configPath}: ${parsed.error}` };
    }
    return parsed;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    return { ok: false, error: `Invalid ${configPath}: ${message}` };
  }
}

export function readProjectPolicyPatch(cwd: string): IParseResult<ICompactionPolicyPatch> {
  const globalConfigPath = resolveGlobalCompactionPolicyPath();
  const projectPath = join(cwd, CONFIG_FILE);
  if (existsSync(projectPath)) {return readConfigFile(projectPath);}
  if (existsSync(globalConfigPath)) {return readConfigFile(globalConfigPath);}
  return { ok: true, value: {} };
}
