import { test, expect } from "@playwright/test";
import { login } from "@open-mercato/core/modules/core/__integration__/helpers/auth";
test.describe("TC-AI-PLAYGROUND-004: AI Playground", () => {
  const playgroundPath = "/backend/config/ai-assistant/playground";
  test("playground renders agent picker or empty state for superadmin", async ({ page }) => {
    await login(page, "superadmin");
    await page.route("**/api/ai_assistant/ai/agents", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          agents: [
            {
              id: "customers.assistant",
              moduleId: "customers",
              label: "Customers assistant",
              description: "Answers questions about customer records.",
              executionMode: "chat",
              mutationPolicy: "read-only",
              allowedTools: ["customers.list_people"],
              requiredFeatures: [],
              acceptedMediaTypes: [],
              hasOutputSchema: false
            },
            {
              id: "catalog.extract",
              moduleId: "catalog",
              label: "Catalog extractor",
              description: "Extracts structured product metadata.",
              executionMode: "object",
              mutationPolicy: "read-only",
              allowedTools: [],
              requiredFeatures: [],
              acceptedMediaTypes: [],
              hasOutputSchema: true
            }
          ],
          total: 2
        })
      });
    });
    await page.route("**/api/ai_assistant/ai/chat**", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "text/event-stream",
        body: "ok from stubbed SSE\n"
      });
    });
    await page.route("**/api/ai_assistant/ai/run-object", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          object: { title: "Stubbed title" },
          finishReason: "stop",
          usage: { inputTokens: 1, outputTokens: 2 }
        })
      });
    });
    await page.goto(playgroundPath, { waitUntil: "domcontentloaded" });
    const container = page.locator("[data-ai-playground]");
    const empty = page.getByText(/No AI agents are registered/i).first();
    const loadError = page.locator("[data-ai-playground-error]");
    await expect(container.or(empty).or(loadError)).toBeVisible({ timeout: 15e3 });
    if (await container.isVisible().catch(() => false)) {
      const picker = page.locator("[data-ai-playground-agent-picker]");
      await expect(picker).toBeVisible();
      const optionCount = await picker.locator("option").count();
      expect(optionCount).toBeGreaterThanOrEqual(2);
      const debugToggle = page.locator("[data-ai-playground-debug-toggle]");
      await expect(debugToggle).toBeVisible();
      const composer = page.locator("#ai-chat-composer");
      await expect(composer).toBeVisible();
      await composer.fill("Hello from Playwright");
      await expect(composer).toHaveValue("Hello from Playwright");
      const debugPanel = page.locator('[data-ai-chat-debug="true"]');
      const initiallyVisible = await debugPanel.isVisible().catch(() => false);
      if (!initiallyVisible) {
        await debugToggle.click();
      }
      await expect(debugPanel).toBeVisible({ timeout: 5e3 });
      await expect(
        page.locator('[data-ai-chat-debug-section="tools"]')
      ).toBeVisible();
      await expect(
        page.locator('[data-ai-chat-debug-section="promptSections"]')
      ).toBeVisible();
      await expect(
        page.locator('[data-ai-chat-debug-section="lastRequest"]')
      ).toBeVisible();
    } else if (await empty.isVisible().catch(() => false)) {
      await expect(empty).toBeVisible();
    } else {
      await expect(loadError).toBeVisible();
    }
  });
  test("picker lists all three Phase 2 agents and chat-mode selection disables object-mode tab", async ({
    page
  }) => {
    test.setTimeout(12e4);
    await login(page, "superadmin");
    await page.goto(playgroundPath, { waitUntil: "domcontentloaded" });
    const container = page.locator("[data-ai-playground]");
    await expect(container).toBeVisible({ timeout: 6e4 });
    const picker = page.locator("[data-ai-playground-agent-picker]");
    await expect(picker).toBeVisible();
    await expect(
      picker.locator('option[value="customers.account_assistant"]')
    ).toHaveCount(1);
    await expect(
      picker.locator('option[value="catalog.catalog_assistant"]')
    ).toHaveCount(1);
    await expect(
      picker.locator('option[value="catalog.merchandising_assistant"]')
    ).toHaveCount(1);
    await page.getByRole("tab", { name: /object mode/i }).click();
    await expect(
      page.locator('[data-ai-playground-unsupported="object"]')
    ).toBeVisible();
    await page.getByRole("tab", { name: /^chat$/i }).click();
    const chatRegion = page.locator("[data-ai-chat-agent]").first();
    await expect(chatRegion).toBeVisible();
  });
  test("chat happy path \u2014 stubbed SSE response appears in the transcript", async ({ page }) => {
    test.setTimeout(12e4);
    await login(page, "superadmin");
    await page.route("**/api/ai_assistant/ai/agents", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          agents: [
            {
              id: "customers.account_assistant",
              moduleId: "customers",
              label: "Customers account assistant",
              description: "Stubbed agent for playground chat smoke.",
              executionMode: "chat",
              mutationPolicy: "read-only",
              allowedTools: [],
              requiredFeatures: [],
              acceptedMediaTypes: [],
              hasOutputSchema: false
            }
          ],
          total: 1
        })
      });
    });
    const streamBody = [
      "event: text",
      'data: {"content":"stubbed-playground-reply"}',
      "",
      "event: done",
      "data: {}",
      ""
    ].join("\n");
    await page.route("**/api/ai_assistant/ai/chat**", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "text/event-stream",
        body: streamBody
      });
    });
    await page.goto(playgroundPath, { waitUntil: "domcontentloaded" });
    const composer = page.locator("#ai-chat-composer");
    await expect(composer).toBeVisible({ timeout: 6e4 });
    await composer.fill("Say hi please");
    await composer.press("Meta+Enter");
    await page.waitForTimeout(200);
    if (!await page.locator('[data-ai-chat-state="thinking"]').count()) {
      await composer.press("Control+Enter");
    }
    await expect(async () => {
      const cleared = await composer.inputValue() === "";
      const rendered = await page.getByText(/stubbed-playground-reply/i).count();
      const thinking = await page.locator('[data-ai-chat-state="thinking"]').count();
      expect(cleared || rendered > 0 || thinking > 0).toBe(true);
    }).toPass({ timeout: 1e4 });
  });
  test("mutation-preview-card renders inside the playground transcript when a pending action is emitted", async ({
    page
  }) => {
    test.setTimeout(12e4);
    await login(page, "superadmin");
    await page.route("**/api/ai_assistant/ai/agents", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          agents: [
            {
              id: "customers.account_assistant",
              moduleId: "customers",
              label: "Customers account assistant",
              description: "Mutation-capable agent for Phase 3 approval flow.",
              executionMode: "chat",
              mutationPolicy: "require-approval",
              allowedTools: ["customers.update_person"],
              requiredFeatures: [],
              acceptedMediaTypes: [],
              hasOutputSchema: false
            }
          ],
          total: 1
        })
      });
    });
    const pendingRow = {
      pendingAction: {
        id: "pa-stub-001",
        agentId: "customers.account_assistant",
        toolName: "customers.update_person",
        status: "pending",
        fieldDiff: [
          { field: "name", before: "Alice", after: "Alicia" }
        ],
        records: null,
        failedRecords: null,
        sideEffectsSummary: "Rename Alice to Alicia.",
        attachmentIds: [],
        targetEntityType: "customers.person",
        targetRecordId: "p-1",
        recordVersion: "1",
        executionResult: null,
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        expiresAt: new Date(Date.now() + 6e5).toISOString(),
        resolvedAt: null,
        resolvedByUserId: null
      }
    };
    await page.route("**/api/ai_assistant/ai/actions/pa-stub-001", async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify(pendingRow)
      });
    });
    await page.goto(
      `${playgroundPath}?uiPart=mutation-preview-card&pendingActionId=pa-stub-001`,
      { waitUntil: "domcontentloaded" }
    );
    const container = page.locator("[data-ai-playground]");
    await expect(container).toBeVisible({ timeout: 6e4 });
    const previewCard = page.locator("[data-ai-mutation-preview]").first();
    await expect(previewCard).toBeVisible({ timeout: 15e3 });
    await expect(page.locator("[data-ai-mutation-preview-confirm]")).toBeVisible();
    await expect(page.locator("[data-ai-mutation-preview-cancel]")).toBeVisible();
  });
});
//# sourceMappingURL=TC-AI-PLAYGROUND-004-playground.spec.js.map
