#!/usr/bin/env node

import http from "node:http";
import { chmodSync, mkdtempSync, readFileSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "node:child_process";

const pluginRoot = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
const root = mkdtempSync(join(tmpdir(), "carbon-integrations-project-"));
const home = mkdtempSync(join(tmpdir(), "carbon-integrations-home-"));
chmodSync(root, 0o700);
chmodSync(home, 0o700);
const writes = [];
const mock = http.createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  if (req.url.includes("get_cases/41")) return reply(res, { offset: 0, limit: 25, size: 1, cases: [{ id: 7, title: "Login rejects a locked user", priority_id: 1 }] });
  if (req.url.includes("get_results_for_run/91")) return reply(res, [{ id: 8, case_id: 7, status_id: 5, comment: "Known failure" }]);
  if (req.url.includes("add_case/12") && req.method === "POST") {
    writes.push(JSON.parse(body));
    return reply(res, { id: 88, title: writes.at(-1).title });
  }
  return reply(res, { error: `unexpected ${req.method} ${req.url}` }, 404);
});
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
const baseUrl = `http://127.0.0.1:${mock.address().port}`;

function reply(res, value, status = 200) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(value));
}

const child = spawn(process.execPath, [join(pluginRoot, "server", "index.js")], {
  cwd: root,
  env: {
    ...process.env,
    HOME: home,
    CARBON_CREDENTIAL_STORE: "file",
    TESTRAIL_BASE_URL: baseUrl,
    TESTRAIL_EMAIL: "quality@example.com",
    TESTRAIL_API_KEY: "test-secret-never-returned",
    TESTRAIL_PROJECT_ID: "41",
    TESTRAIL_SECTION_ID: "12",
    TESTRAIL_RUN_IDS: "91",
  },
  stdio: ["pipe", "pipe", "pipe"],
});
let buffer = "";
let id = 1;
const pending = new Map();
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
  buffer += chunk;
  while (buffer.includes("\n")) {
    const at = buffer.indexOf("\n");
    const line = buffer.slice(0, at).trim();
    buffer = buffer.slice(at + 1);
    if (!line) continue;
    const message = JSON.parse(line);
    if (pending.has(message.id)) { pending.get(message.id)(message.result); pending.delete(message.id); }
  }
});
function request(method, params = {}) {
  const requestId = id++;
  child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: requestId, method, params })}\n`);
  return new Promise((resolve) => pending.set(requestId, resolve));
}
function textResult(result) {
  return JSON.parse(result.content[0].text);
}
try {
  await request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "integration-contract", version: "1" } });
  const status = textResult(await request("tools/call", { name: "carbon_get_integration_status", arguments: { root } }));
  if (!status.providers.testrail.configured || JSON.stringify(status).includes("test-secret-never-returned")) throw new Error("secret-safe TestRail readiness failed");

  const snapshot = textResult(await request("tools/call", { name: "carbon_read_external_quality", arguments: { root, provider: "testrail", maxItems: 25 } }));
  if (snapshot.evidence.cases[0].id !== 7 || snapshot.evidence.results[0].data[0].case_id !== 7) throw new Error("external cases/results were not normalized");
  if (!statSync(snapshot.snapshotPath).isFile()) throw new Error("durable external snapshot missing");

  const rejectedDelete = textResult(await request("tools/call", { name: "carbon_preview_integration_sync", arguments: { root, provider: "testrail", operations: [{ action: "delete-test", externalId: "7", payload: {} }] } }));
  if (!String(rejectedDelete.error || "").includes("Deletes are never supported")) throw new Error("delete preview was not rejected");

  const preview = textResult(await request("tools/call", { name: "carbon_preview_integration_sync", arguments: { root, provider: "testrail", operations: [{ action: "create-test", payload: { title: "Carbon generated boundary case", custom_steps_separated: [{ content: "Submit empty username", expected: "Validation blocks submission" }] } }] } }));
  const blocked = textResult(await request("tools/call", { name: "carbon_apply_integration_sync", arguments: { root, planDigest: preview.digest, confirm: true, backupConfirmed: false } }));
  if (!String(blocked.error || "").includes("backupConfirmed=true") || writes.length) throw new Error("backup gate failed closed incorrectly");
  const applied = textResult(await request("tools/call", { name: "carbon_apply_integration_sync", arguments: { root, planDigest: preview.digest, confirm: true, backupConfirmed: true } }));
  if (applied.operationCount !== 1 || writes.length !== 1 || !readFileSync(applied.auditPath, "utf8").includes(preview.digest)) throw new Error("approved sync or audit failed");
  console.log("PASS: Jira/Xray/TestRail settings are secret-safe; TestRail reads produce durable observed snapshots; deletes fail closed; external writes require unchanged preview, explicit approval, backup confirmation, and local audit evidence.");
} finally {
  child.kill("SIGTERM");
  mock.close();
}
