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 { BUNDLE_TOOL_SEARCH_DEFAULTS, ensureToolSearchDefaults, readToolSearchConfig } from "../extensions/config.ts";

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

test("writes bundle defaults when toolSearch is absent", async () => {
  await withAgentDir(async (agentDir) => {
    assert.equal(ensureToolSearchDefaults(agentDir), "updated");
    assert.deepEqual(JSON.parse(await readFile(join(agentDir, "settings.json"), "utf8")), {
      toolSearch: {
        alwaysEnabled: [...BUNDLE_TOOL_SEARCH_DEFAULTS.alwaysEnabled],
        showToolSearchFooterStatus: false,
        maxActiveGroups: 3,
        maxToolsPerGroup: 8,
        maxDynamicTools: 20,
        groupOverrides: {},
      },
    });
  });
});

test("fills missing defaults and preserves explicit settings", async () => {
  await withAgentDir(async (agentDir) => {
    const path = join(agentDir, "settings.json");
    await writeFile(path, JSON.stringify({ theme: "dark", toolSearch: { alwaysEnabled: ["multi_grep"], maxActiveGroups: 2 } }), "utf8");
    assert.equal(ensureToolSearchDefaults(agentDir), "updated");
    assert.deepEqual(JSON.parse(await readFile(path, "utf8")), {
      theme: "dark",
      toolSearch: {
        alwaysEnabled: ["multi_grep"],
        maxActiveGroups: 2,
        showToolSearchFooterStatus: false,
        maxToolsPerGroup: 8,
        maxDynamicTools: 20,
        groupOverrides: {},
      },
    });
  });
});

test("normalizes invalid runtime values without overwriting the file", async () => {
  await withAgentDir(async (agentDir) => {
    const path = join(agentDir, "settings.json");
    const original = JSON.stringify({
      toolSearch: {
        alwaysEnabled: ["one", "one", 3],
        showToolSearchFooterStatus: "no",
        maxActiveGroups: 0,
        maxToolsPerGroup: 4,
        maxDynamicTools: -1,
        groupOverrides: { web: ["search", 2], empty: [] },
      },
    });
    await writeFile(path, original, "utf8");
    assert.deepEqual(readToolSearchConfig(agentDir), {
      alwaysEnabled: ["one"],
      showToolSearchFooterStatus: false,
      maxActiveGroups: 3,
      maxToolsPerGroup: 4,
      maxDynamicTools: 20,
      groupOverrides: { web: ["search"] },
    });
    assert.equal(await readFile(path, "utf8"), original);
  });
});

test("preserves explicit complete configuration", async () => {
  await withAgentDir(async (agentDir) => {
    const path = join(agentDir, "settings.json");
    const original = `${JSON.stringify({
      toolSearch: {
        alwaysEnabled: [],
        showToolSearchFooterStatus: true,
        maxActiveGroups: 1,
        maxToolsPerGroup: 2,
        maxDynamicTools: 2,
        groupOverrides: { custom: ["one"] },
      },
    }, null, 2)}\n`;
    await writeFile(path, original, "utf8");
    assert.equal(ensureToolSearchDefaults(agentDir), "unchanged");
    assert.equal(await readFile(path, "utf8"), original);
  });
});

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