import { readFileSync } from "node:fs";
import { isAbsolute, join, resolve } from "node:path";

export function readConfiguredLocalDataRoot(environment: NodeJS.ProcessEnv = process.env) {
  const localAppData = environment.LOCALAPPDATA;
  if (!localAppData || !isAbsolute(localAppData)) throw new Error("local_app_data_unavailable");
  const configFile = join(localAppData, "Dada", "P0A", "config", "instance.json");
  const configuration = JSON.parse(readFileSync(configFile, "utf8")) as Record<string, unknown>;
  const candidate = configuration.data_root ?? configuration.local_data_root;
  if (typeof candidate !== "string" || !isAbsolute(candidate)) throw new Error("data_root_configuration_invalid");
  return resolve(candidate);
}
