// Codex tests cover conversation control plugin behavior.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { clearRuntimeAuthProfileStoreSnapshots } from "openclaw/plugin-sdk/agent-runtime";
import { upsertAuthProfile } from "openclaw/plugin-sdk/provider-auth";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
  readCodexAppServerBinding,
  writeCodexAppServerBinding,
} from "./app-server/session-binding.js";
import {
  setCodexConversationFastMode,
  setCodexConversationModel,
  setCodexConversationPermissions,
} from "./conversation-control.js";

let tempDir: string;

const sharedClientMocks = vi.hoisted(() => ({
  getSharedCodexAppServerClient: vi.fn(),
}));

vi.mock("./app-server/shared-client.js", () => ({
  ...sharedClientMocks,
  getLeasedSharedCodexAppServerClient: sharedClientMocks.getSharedCodexAppServerClient,
  releaseLeasedSharedCodexAppServerClient: vi.fn(),
}));

describe("codex conversation controls", () => {
  beforeEach(async () => {
    tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-control-"));
    vi.stubEnv("OPENCLAW_STATE_DIR", tempDir);
    sharedClientMocks.getSharedCodexAppServerClient.mockReset();
  });

  afterEach(async () => {
    vi.unstubAllEnvs();
    clearRuntimeAuthProfileStoreSnapshots();
    await fs.rm(tempDir, { recursive: true, force: true });
  });

  it("persists fast mode and permissions for later bound turns", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      model: "gpt-5.4",
      modelProvider: "openai",
      approvalPolicy: "never",
      sandbox: "danger-full-access",
    });

    await expect(setCodexConversationFastMode({ sessionFile, enabled: true })).resolves.toBe(
      "Codex fast mode enabled.",
    );
    await expect(setCodexConversationPermissions({ sessionFile, mode: "default" })).resolves.toBe(
      "Codex permissions set to default.",
    );

    const binding = await readCodexAppServerBinding(sessionFile);
    expect(binding?.threadId).toBe("thread-1");
    expect(binding?.serviceTier).toBe("priority");
    expect(binding?.approvalPolicy).toBe("on-request");
    expect(binding?.sandbox).toBe("workspace-write");
  });

  it("does not persist public OpenAI provider after model changes on native auth bindings", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    const agentDir = path.join(tempDir, "agents", "bot-a", "agent");
    upsertAuthProfile({
      profileId: "work",
      credential: {
        type: "oauth",
        provider: "openai",
        access: "access-token",
        refresh: "refresh-token",
        expires: Date.now() + 60_000,
      },
    });
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      authProfileId: "work",
      model: "gpt-5.4",
      modelProvider: "openai",
    });
    sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
      request: vi.fn(async () => ({
        thread: { id: "thread-1", cwd: tempDir },
        model: "gpt-5.5",
        modelProvider: "openai",
      })),
    });

    await expect(
      setCodexConversationModel({ sessionFile, agentDir, model: "gpt-5.5" }),
    ).resolves.toBe("Codex model set to gpt-5.5.");

    const raw = await fs.readFile(`${sessionFile}.codex-app-server.json`, "utf8");
    const binding = await readCodexAppServerBinding(sessionFile);
    const sharedClientParams = sharedClientMocks.getSharedCodexAppServerClient.mock.calls[0]?.[0];
    expect(sharedClientParams?.agentDir).toBe(agentDir);
    expect(raw).not.toContain('"modelProvider": "openai"');
    expect(binding?.threadId).toBe("thread-1");
    expect(binding?.authProfileId).toBe("work");
    expect(binding?.model).toBe("gpt-5.5");
    expect(binding?.modelProvider).toBeUndefined();
  });

  it("keeps Guardian reviewer when switching a stale local binding to a provider-qualified OpenAI model", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      model: "local-model",
      modelProvider: "lmstudio",
      approvalPolicy: "on-request",
      sandbox: "workspace-write",
    });
    const request = vi.fn(async (_method: string, _requestParams?: unknown) => ({
      thread: { id: "thread-1", cwd: tempDir },
      model: "gpt-5.5",
      modelProvider: "openai",
    }));
    sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({ request });

    await expect(
      setCodexConversationModel({
        sessionFile,
        model: "openai/gpt-5.5",
        pluginConfig: { appServer: { mode: "guardian" } },
      }),
    ).resolves.toBe("Codex model set to gpt-5.5.");

    const resumeParams = request.mock.calls[0]?.[1] as Record<string, unknown> | undefined;
    const binding = await readCodexAppServerBinding(sessionFile);
    expect(resumeParams?.model).toBe("gpt-5.5");
    expect(resumeParams?.modelProvider).toBe("openai");
    expect(resumeParams?.approvalsReviewer).toBe("auto_review");
    expect(binding?.modelProvider).toBe("openai");
  });

  it("keeps the bound local provider when switching to another unqualified model", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      model: "local-model",
      modelProvider: "lmstudio",
      approvalPolicy: "on-request",
      sandbox: "workspace-write",
    });
    const request = vi.fn(async (_method: string, _requestParams?: unknown) => ({
      thread: { id: "thread-1", cwd: tempDir },
      model: "local-model-2",
      modelProvider: "lmstudio",
    }));
    sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({ request });

    await expect(
      setCodexConversationModel({
        sessionFile,
        model: "local-model-2",
        pluginConfig: { appServer: { mode: "guardian" } },
      }),
    ).resolves.toBe("Codex model set to local-model-2.");

    const resumeParams = request.mock.calls[0]?.[1] as Record<string, unknown> | undefined;
    expect(resumeParams?.model).toBe("local-model-2");
    expect(resumeParams?.modelProvider).toBe("lmstudio");
    expect(resumeParams?.approvalsReviewer).toBe("user");
  });

  it("keeps the bound local provider when reselecting a model id with a slash", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      model: "openai/gpt-oss-20b",
      modelProvider: "lmstudio",
      approvalPolicy: "on-request",
      sandbox: "workspace-write",
    });
    const request = vi.fn(async (_method: string, _requestParams?: unknown) => ({
      thread: { id: "thread-1", cwd: tempDir },
      model: "openai/gpt-oss-20b",
      modelProvider: "lmstudio",
    }));
    sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({ request });

    await expect(
      setCodexConversationModel({
        sessionFile,
        model: "openai/gpt-oss-20b",
        pluginConfig: { appServer: { mode: "guardian" } },
      }),
    ).resolves.toBe("Codex model set to openai/gpt-oss-20b.");

    const resumeParams = request.mock.calls[0]?.[1] as Record<string, unknown> | undefined;
    const binding = await readCodexAppServerBinding(sessionFile);
    expect(resumeParams?.model).toBe("openai/gpt-oss-20b");
    expect(resumeParams?.modelProvider).toBe("lmstudio");
    expect(resumeParams?.approvalsReviewer).toBe("user");
    expect(binding?.modelProvider).toBe("lmstudio");
  });

  it("escapes model names returned from Codex before chat display", async () => {
    const sessionFile = path.join(tempDir, "session.jsonl");
    await writeCodexAppServerBinding(sessionFile, {
      threadId: "thread-1",
      cwd: tempDir,
      model: "gpt-5.4",
      modelProvider: "openai",
    });
    sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
      request: vi.fn(async () => ({
        thread: { id: "thread-1", cwd: tempDir },
        model: "gpt-5.5 <@U123> [trusted](https://evil)",
        modelProvider: "openai",
      })),
    });

    await expect(setCodexConversationModel({ sessionFile, model: "gpt-5.5" })).resolves.toBe(
      "Codex model set to gpt-5.5 &lt;\uff20U123&gt; \uff3btrusted\uff3d\uff08https://evil\uff09.",
    );
  });
});
