#!/usr/bin/env node
"use strict";

const assert = require("node:assert");

const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const REQUEST_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_TIMEOUT_MS || 20_000);

async function fetchWithTimeout(path, init = {}) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  try {
    return await fetch(`${BASE_URL}${path}`, { ...init, signal: controller.signal });
  } finally {
    clearTimeout(timeout);
  }
}

async function main() {
  const response = await fetchWithTimeout("/api/ai-agent/run", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      stream: true,
      messages: [{ role: "user", content: "ping" }],
      context: { documentId: "retirement_guard" },
      options: { ai: { provider: "hermes" } },
    }),
  });
  const text = await response.text();
  let payload = null;
  try {
    payload = JSON.parse(text);
  } catch {
    payload = { raw: text };
  }

  assert(
    response.status === 410,
    `/api/ai-agent/run legacy guard 应返回退场状态，实际 ${response.status}: ${text.slice(0, 500)}`,
  );
  const code = response.headers.get("x-error-code") || payload.code || "";
  const owner = response.headers.get("x-mnote-ai-execution-owner") || "";
  assert(
    code === "legacy_ai_agent_run_retired" && owner.includes("retired"),
    `legacy guard 不应静默 fallback，code=${code}, owner=${owner}, body=${text.slice(0, 500)}`,
  );

  console.log(
    JSON.stringify(
      {
        ok: true,
        baseUrl: BASE_URL,
        status: response.status,
        code,
        owner,
      },
      null,
      2,
    ),
  );
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
