import { test, expect } from '@playwright/test';
import { BASE_URL, ensureLoggedIn } from './helpers/auth';

// ─────────────────────────────────────────────────────────────────────────────
// 6. CHATBOT — Tính năng AI / CuCu Assistant
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Navigate to the chatbot — it can be a dedicated page or a panel widget.
 * CuCu Note uses ChatbotPanel embedded in the Home page or a /chat route.
 */
async function goToChatbot(page: import('@playwright/test').Page): Promise<boolean> {
  await page.goto(`${BASE_URL}/app`, { waitUntil: 'domcontentloaded' });

  // First try: dedicated sidebar nav link for chat
  const chatLink = page
    .locator('a[href*="chat"], a[href*="ai"]')
    .or(page.locator('#header-chat'))
    .first();

  try {
    await chatLink.waitFor({ state: 'visible', timeout: 4000 });
    await chatLink.click();
    await page.waitForTimeout(1000);
  } catch {
    // Second try: direct /app/chat route
    await page.goto(`${BASE_URL}/app/chat`, { waitUntil: 'domcontentloaded' });
    if (page.url().includes('/auth')) return false;
  }

  // Verify chat input is visible
  const chatInput = page.locator('[data-testid="chat-input"]');
  try {
    await chatInput.waitFor({ state: 'visible', timeout: 8000 });
    return true;
  } catch {
    // Try: chat panel might be embedded in app home — look for the widget
    const widget = page.locator('[class*="chatbot"], [class*="chat-panel"]').first();
    try {
      await widget.waitFor({ state: 'visible', timeout: 5000 });
      return true;
    } catch {
      return false;
    }
  }
}

test.describe('6. Chatbot — Tính năng AI', () => {
  test.beforeEach(async ({ page }) => {
    await ensureLoggedIn(page);
  });

  test('6.1 Chatbot panel có thể mở và hiển thị chat input', async ({ page }) => {
    const available = await goToChatbot(page);
    if (!available) {
      console.log('[6.1] Chatbot not accessible at this time — soft skip');
      test.skip();
      return;
    }

    // Chat input must be visible
    await expect(page.locator('[data-testid="chat-input"]')).toBeVisible({ timeout: 10000 });
    // Send button must be visible
    await expect(page.locator('[data-testid="chat-send"]')).toBeVisible({ timeout: 5000 });
    console.log('[6.1] Chatbot UI rendered OK');
  });

  test('6.2 Gửi câu chào hỏi đơn giản → AI trả lời (streaming)', async ({ page }) => {
    const available = await goToChatbot(page);
    if (!available) {
      test.skip();
      return;
    }

    const chatInput = page.locator('[data-testid="chat-input"]');
    await chatInput.waitFor({ state: 'visible', timeout: 10000 });
    await chatInput.fill('Xin chào! Bạn là ai?');

    // Click send
    await page.locator('[data-testid="chat-send"]').click();

    // AI message should appear — using data-testid="ai-message"
    const aiResponse = page.locator('[data-testid="ai-message"]').last();
    await expect(aiResponse).toBeVisible({ timeout: 35000 });

    // Response should have non-trivial content
    const responseText = await aiResponse.textContent();
    expect((responseText ?? '').trim().length).toBeGreaterThan(3);
    console.log(`[6.2] AI response: "${responseText?.slice(0, 100)}..."`);
  });

  test('6.3 RAG — Hỏi AI tổng hợp ghi chú theo từ khóa', async ({ page }) => {
    // First create a memo with unique keyword for RAG validation
    await page.goto(`${BASE_URL}/app`, { waitUntil: 'domcontentloaded' });

    const uniqueKeyword = `RAGTEST${Date.now()}`;
    const textarea = page.locator('[data-testid="memo-editor-textarea"]').first();
    await textarea.waitFor({ state: 'visible', timeout: 12000 });
    await textarea.click();
    await textarea.fill(`Đây là ghi chú test RAG với từ khóa đặc biệt: ${uniqueKeyword}`);
    await page.locator('[data-testid="memo-editor-save"]').first().click();
    await expect(page.getByText(uniqueKeyword, { exact: false })).toBeVisible({ timeout: 15000 });

    // Navigate to chatbot
    const available = await goToChatbot(page);
    if (!available) {
      console.log('[6.3] Chatbot not accessible — skipping RAG test');
      test.skip();
      return;
    }

    const chatInput = page.locator('[data-testid="chat-input"]');
    await chatInput.waitFor({ state: 'visible', timeout: 10000 });
    await chatInput.fill(`Tổng hợp các ghi chú có từ khóa ${uniqueKeyword}`);
    await page.locator('[data-testid="chat-send"]').click();

    // Wait for AI response
    const aiResponse = page.locator('[data-testid="ai-message"]').last();
    await expect(aiResponse).toBeVisible({ timeout: 35000 });

    const text = await aiResponse.textContent();
    expect((text ?? '').trim().length).toBeGreaterThan(10);
    console.log(`[6.3] RAG response: "${text?.slice(0, 100)}..."`);
  });

  test('6.4 Chatbot không crash sau nhiều tin nhắn liên tiếp', async ({ page }) => {
    const available = await goToChatbot(page);
    if (!available) {
      test.skip();
      return;
    }

    const chatInput = page.locator('[data-testid="chat-input"]');
    const sendBtn = page.locator('[data-testid="chat-send"]');

    const messages = [
      'Hôm nay tôi có bao nhiêu ghi chú?',
      'Hiển thị ghi chú gần nhất',
    ];

    for (const msg of messages) {
      await chatInput.waitFor({ state: 'visible', timeout: 8000 });
      await chatInput.fill(msg);
      await sendBtn.click();

      // Wait for AI response before sending next
      const aiMsgs = page.locator('[data-testid="ai-message"]');
      const countBefore = await aiMsgs.count();
      await expect(aiMsgs.nth(countBefore)).toBeVisible({ timeout: 35000 }).catch(() => {
        // Might be same index if count didn't increase yet
      });
      await page.waitForTimeout(2000);
    }

    // No crash — page still renders
    await expect(page.locator('body')).not.toContainText(/crashed|500|error/i);
    console.log('[6.4] Multi-message chat OK');
  });
});
