import assert from "node:assert/strict";
import test from "node:test";

import {
  buildCodexAppServerArgs,
  buildCodexCliConfig,
  buildCodexCliExecArgs,
  CodexCliAdapter,
  isSafeSdkAgentId,
} from "../CodexCliAdapter.ts";

test("subscription invocation uses bidirectional app-server without an API key", () => {
  const args = buildCodexAppServerArgs({
    mcpServers: {
      fcop: {
        command: "python",
        args: ["-m", "fcop_mcp"],
        env: { FCOP_PROJECT_DIR: "D:\\workspace" },
        cwd: "D:\\workspace",
      },
    },
  });

  assert.deepEqual(args.slice(0, 2), ["app-server", "--stdio"]);
  assert.ok(args.includes('model_provider="openai"'));
  assert.ok(args.includes('approval_policy="never"'));
  assert.ok(args.includes('approvals_reviewer="auto_review"'));
  assert.ok(args.some((value) => value.includes("mcp_servers.fcop.command")));
  assert.ok(args.some((value) => value.includes("FCOP_PROJECT_DIR")));
  assert.ok(args.some((value) => value.includes("mcp_servers.fcop.cwd")));
  assert.ok(!args.some((value) => /api[_-]?key/i.test(value)));
});

test("custom-provider invocation remains one-way JSONL exec", () => {
  const args = buildCodexCliExecArgs({
    authMode: "custom-provider",
    workspace: "D:\\workspace",
    model: "doubao",
    text: "hello",
  });
  assert.deepEqual(args.slice(0, 2), ["exec", "--json"]);
  assert.equal(args.at(-1), "hello");
});

test("custom-provider config remains Responses-only and never embeds the secret", () => {
  const config = buildCodexCliConfig({
    model: "doubao-seed-2-0-pro-260215",
    apiKeyEnv: "ARK_API_KEY",
  });
  assert.match(config, /wire_api = "responses"/);
  assert.match(config, /requires_openai_auth = false/);
  assert.match(config, /env_key = "ARK_API_KEY"/);
  assert.doesNotMatch(config, /sk-[A-Za-z0-9]/);
});

test("subscription adapter needs no OpenAI API key", async () => {
  const adapter = new CodexCliAdapter({
    authMode: "chatgpt-subscription",
    defaultModel: "gpt-5.6-sol",
    probeVersion: async () => undefined,
  });
  assert.deepEqual(await adapter.listModels(), ["gpt-5.6-sol"]);
  assert.deepEqual(await adapter.create({
    agentId: "PM-01",
    role: "PM",
    layer: "leader",
    runtime: "local",
  }), {
    sdk_agent_id: "codex-cli:PM-01",
  });
});

test("adapter accepts a persisted registry SDK id after a provider switch", async () => {
  const adapter = new CodexCliAdapter({
    authMode: "chatgpt-subscription",
    defaultModel: "gpt-5.6-sol",
    probeVersion: async () => undefined,
  });
  const persistedId = "agent-4acf5e85-3ae4-4b31-82b9-de43d49226ea";

  assert.equal(isSafeSdkAgentId(persistedId), true);
  await adapter.resume(persistedId);
  assert.deepEqual(await adapter.list(), [persistedId]);
  assert.equal(isSafeSdkAgentId("../unsafe id"), false);
});
