import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";

export type CondenseDefaultResult = "updated" | "unchanged" | "skipped-invalid";

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

/** Enable pi-condense only when the user has not already chosen an enabled state. */
export function ensureCondenseEnabledDefault(agentDir: string): CondenseDefaultResult {
	const targetPath = join(agentDir, "settings.json");
	let settings: Record<string, unknown> = {};

	try {
		const parsed: unknown = JSON.parse(readFileSync(targetPath, "utf8"));
		if (!isObject(parsed)) return "skipped-invalid";
		settings = parsed;
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "skipped-invalid";
	}

	const existing = settings.contextPrune;
	if (existing !== undefined && !isObject(existing)) return "skipped-invalid";
	if (isObject(existing) && Object.hasOwn(existing, "enabled")) return "unchanged";

	settings.contextPrune = { ...(existing ?? {}), enabled: true };
	mkdirSync(dirname(targetPath), { recursive: true });
	const temporaryPath = `${targetPath}.my-pi.tmp`;
	writeFileSync(temporaryPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
	renameSync(temporaryPath, targetPath);
	return "updated";
}
