import { test, expect } from '@playwright/test'
import {
  loginAndHydrate,
  sendChatMessage,
  waitForLlmResponse,
  LLM_RESPONSE_TIMEOUT_MS,
} from './helpers'

test.describe('Chat flow', () => {
  test.beforeEach(async ({ page }) => {
    // Authenticate via API and hydrate localStorage before navigating
    await loginAndHydrate(page)
    await page.goto('/agent/chat')

    // Wait for the chat view to mount — the input textarea should be visible
    await expect(page.getByPlaceholder('输入消息，按 Enter 发送...')).toBeVisible({
      timeout: 15_000,
    })
  })

  test('should send a message and receive a real LLM response', async ({ page }) => {
    const testMessage = '你好，请用一句话介绍自己'

    // Send the message
    await sendChatMessage(page, testMessage)

    // The user's message should appear immediately in the chat view.
    // Use .last() because the conversation may contain prior messages.
    const userMessage = page.locator('.message-shell--user .user-bubble')
    await expect(userMessage.last()).toContainText('你好', { timeout: 10_000 })

    // Wait for the real LLM response (up to 60 seconds).
    // The assistant message is rendered inside .message-shell--assistant
    // with markdown content in .assistant-text__markdown.
    test.setTimeout(LLM_RESPONSE_TIMEOUT_MS + 30_000)
    await waitForLlmResponse(page, expect, LLM_RESPONSE_TIMEOUT_MS)

    // The response should contain some text (non-empty, non-error)
    const assistantContent = page.locator(
      '.message-shell--assistant .assistant-text__markdown',
    )
    const responseText = (await assistantContent.last().textContent()) ?? ''
    expect(responseText.trim().length).toBeGreaterThan(0)

    // The response should not be an error message
    const errorCard = page.locator('.message-shell--assistant .error-card')
    await expect(errorCard).toHaveCount(0)
  })

  test('should display both user and assistant messages in history', async ({ page }) => {
    const testMessage = '1+1等于几？请只回答数字'

    await sendChatMessage(page, testMessage)

    // Verify user message is displayed (use .last() for most recent)
    await expect(
      page.locator('.message-shell--user .user-bubble').last(),
    ).toContainText('1+1', { timeout: 10_000 })

    // Wait for assistant response
    test.setTimeout(LLM_RESPONSE_TIMEOUT_MS + 30_000)
    await waitForLlmResponse(page, expect, LLM_RESPONSE_TIMEOUT_MS)

    // Both user and assistant message shells should be present
    const userMessages = page.locator('.message-shell--user')
    const assistantMessages = page.locator('.message-shell--assistant')

    await expect(userMessages.first()).toBeVisible()
    await expect(assistantMessages.first()).toBeVisible()

    // There should be at least one user message and one assistant message
    expect(await userMessages.count()).toBeGreaterThanOrEqual(1)
    expect(await assistantMessages.count()).toBeGreaterThanOrEqual(1)
  })

  test('should clear input after sending', async ({ page }) => {
    const textarea = page.getByPlaceholder('输入消息，按 Enter 发送...')

    await textarea.fill('测试消息清空')
    await textarea.press('Enter')

    // The textarea should be cleared after sending
    await expect(textarea).toHaveText('', { timeout: 5_000 })
  })
})
