import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";

import { ensureCondenseEnabledDefault } from "../extensions/condense-config.ts";

async function withAgentDir(run: (agentDir: string) => Promise<void>): Promise<void> {
	const agentDir = await mkdtemp(join(tmpdir(), "my-pi-condense-"));
	try {
		await run(agentDir);
	} finally {
		await rm(agentDir, { recursive: true, force: true });
	}
}

test("pi-condense defaults to enabled when contextPrune is absent", async () => {
	await withAgentDir(async (agentDir) => {
		assert.equal(ensureCondenseEnabledDefault(agentDir), "updated");
		assert.deepEqual(JSON.parse(await readFile(join(agentDir, "settings.json"), "utf8")), {
			contextPrune: { enabled: true },
		});
	});
});

test("pi-condense default preserves existing settings and contextPrune fields", async () => {
	await withAgentDir(async (agentDir) => {
		const path = join(agentDir, "settings.json");
		await writeFile(path, JSON.stringify({ theme: "dark", contextPrune: { minBatchChars: 4000 } }), "utf8");
		assert.equal(ensureCondenseEnabledDefault(agentDir), "updated");
		assert.deepEqual(JSON.parse(await readFile(path, "utf8")), {
			theme: "dark",
			contextPrune: { minBatchChars: 4000, enabled: true },
		});
	});
});

test("pi-condense default respects an explicit enabled choice", async () => {
	await withAgentDir(async (agentDir) => {
		const path = join(agentDir, "settings.json");
		const original = `${JSON.stringify({ contextPrune: { enabled: false } }, null, 2)}\n`;
		await writeFile(path, original, "utf8");
		assert.equal(ensureCondenseEnabledDefault(agentDir), "unchanged");
		assert.equal(await readFile(path, "utf8"), original);
	});
});

test("pi-condense default does not overwrite malformed settings", async () => {
	await withAgentDir(async (agentDir) => {
		const path = join(agentDir, "settings.json");
		await writeFile(path, "{not-json", "utf8");
		assert.equal(ensureCondenseEnabledDefault(agentDir), "skipped-invalid");
		assert.equal(await readFile(path, "utf8"), "{not-json");
	});
});
