import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { chmod, mkdtemp, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";

import { parseFrpTomlText } from "./src/deploy-contract-plan.mjs";

const execFileAsync = promisify(execFile);
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");

test("parses FRP TOML tables without Python tomllib", () => {
  const parsed = parseFrpTomlText(`
serverAddr = "74.48.78.17"
serverPort = 7000
loginFailExit = true

[[proxies]]
name = "hwlab-dev-cloud-web"
type = "tcp"
localIP = "hwlab-cloud-web.hwlab-dev.svc.cluster.local"
localPort = 8080
remotePort = 16666

[[proxies]]
name = "hwlab-dev-edge-proxy"
type = "tcp"
localIP = "hwlab-edge-proxy.hwlab-dev.svc.cluster.local"
localPort = 6667
remotePort = 16667
`, "fixture/frpc.dev.toml");

  assert.deepEqual(parsed, {
    serverAddr: "74.48.78.17",
    serverPort: 7000,
    loginFailExit: true,
    proxies: [
      {
        name: "hwlab-dev-cloud-web",
        type: "tcp",
        localIP: "hwlab-cloud-web.hwlab-dev.svc.cluster.local",
        localPort: 8080,
        remotePort: 16666
      },
      {
        name: "hwlab-dev-edge-proxy",
        type: "tcp",
        localIP: "hwlab-edge-proxy.hwlab-dev.svc.cluster.local",
        localPort: 6667,
        remotePort: 16667
      }
    ]
  });
});

test("deploy contract check does not require python3 tomllib", async () => {
  const shimDir = await mkdtemp(path.join(os.tmpdir(), "hwlab-python-shim-"));
  const pythonShim = path.join(shimDir, "python3");
  await writeFile(
    pythonShim,
    [
      "#!/usr/bin/env bash",
      "echo 'ModuleNotFoundError: No module named tomllib' >&2",
      "exit 1",
      ""
    ].join("\n")
  );
  await chmod(pythonShim, 0o755);

  const result = await execFileAsync(process.execPath, ["scripts/deploy-contract-plan.mjs", "--check"], {
    cwd: repoRoot,
    env: {
      ...process.env,
      PATH: `${shimDir}${path.delimiter}${process.env.PATH ?? ""}`
    },
    maxBuffer: 1024 * 1024
  });
  const plan = JSON.parse(result.stdout);

  assert.equal(plan.status, "pass");
  assert.equal(plan.summary.frpProxies, 2);
  assert.deepEqual(plan.diagnostics, []);
});
