"""
階段 3d:@庫柏 mention 自動化測試。

測試:
  1. Robert 進入「閒聊」頻道
  2. 發訊息「@庫柏 你好,自我介紹一下」
  3. 應該在 1 秒內看到「庫柏正在思考...」指示器
  4. 應該在 15 秒內看到庫柏回應(淺藍底 + AI 標籤)
  5. 截圖證明
"""

import asyncio
import sys
import time
from pathlib import Path

try:
    sys.stdout.reconfigure(encoding="utf-8")
except (AttributeError, ValueError):
    pass

from playwright.async_api import async_playwright


HERE = Path(__file__).resolve().parent
PROFILE_DIR = HERE / "profile"
OUT_DIR = HERE / "out"
OUT_DIR.mkdir(exist_ok=True)

BASE_URL = "http://localhost:8000"
ROBERT = {"email": "ssbb30529@gmail.com", "password": "a183b729"}


async def main():
    async with async_playwright() as pw:
        ctx = await pw.chromium.launch_persistent_context(
            user_data_dir=str(PROFILE_DIR / "robert"),
            headless=False,
            args=["--disable-blink-features=AutomationControlled"],
            viewport={"width": 1280, "height": 800},
        )
        results = {"passes": [], "fails": []}

        try:
            page = await ctx.new_page()
            page.set_default_timeout(10000)

            # 強制清空 localStorage 重新登入(避免快取 token 過期)
            await page.goto(BASE_URL, wait_until="domcontentloaded")
            await page.evaluate("localStorage.clear()")
            await page.reload(wait_until="domcontentloaded")
            await page.wait_for_selector("#login-view", state="visible")
            await page.fill("#email", ROBERT["email"])
            await page.fill("#password", ROBERT["password"])
            await page.click("#login-btn")
            await page.wait_for_selector("#dashboard-view", state="visible")
            print("登入成功")

            # 進對話(階段 3e 後是單一頻道,自動選中)
            await page.click('button.section-tab[data-section="chat"]')
            await page.wait_for_function(
                "() => document.querySelectorAll('.chat-message, .chat-empty').length > 0",
                timeout=8000,
            )

            # 記錄目前訊息數
            count_before = await page.locator(".chat-message").count()
            print(f"發送前訊息數:{count_before}")

            # 發 @庫柏 訊息
            stamp = int(time.time())
            mention_text = f"@庫柏 用一句話介紹你自己 [test {stamp}]"
            print(f"\n--- TEST 1:發送「@庫柏」訊息 ---")
            await page.fill("#chat-input", mention_text)
            await page.press("#chat-input", "Enter")

            # ── TEST 1:typing indicator 應該在 2 秒內出現 ──
            t0 = time.time()
            try:
                await page.wait_for_selector("#coba-typing-indicator", state="visible", timeout=2000)
                elapsed = (time.time() - t0) * 1000
                results["passes"].append(f"TEST 1: 「庫柏正在思考」指示器在 {elapsed:.0f}ms 內出現 ✓")
                # 截圖思考中畫面
                await page.screenshot(path=str(OUT_DIR / "coba_thinking.png"), full_page=False)
            except Exception as e:
                results["fails"].append(f"TEST 1: 沒看到 typing 指示器 ({e})")

            # ── TEST 2:庫柏訊息應該在 30 秒內出現 ──
            t0 = time.time()
            try:
                # 等到出現一則 user 為 null 的訊息(coba bubble)
                await page.wait_for_function(
                    """() => {
                        const cobas = document.querySelectorAll('.chat-message.coba');
                        return cobas.length > 0 && Array.from(cobas).some(el => el.querySelector('.chat-msg-bubble'));
                    }""",
                    timeout=30000,
                )
                elapsed = (time.time() - t0) * 1000
                results["passes"].append(f"TEST 2: 庫柏在 {elapsed/1000:.1f} 秒內回應 ✓")
            except Exception as e:
                results["fails"].append(f"TEST 2: 庫柏 30 秒內沒回應 ({e})")

            # ── TEST 3:typing 指示器應該被清掉 ──
            await asyncio.sleep(0.5)
            indicator_count = await page.locator("#coba-typing-indicator").count()
            if indicator_count == 0:
                results["passes"].append("TEST 3: 庫柏回應後,thinking 指示器自動消失 ✓")
            else:
                results["fails"].append(f"TEST 3: 指示器沒清掉(還有 {indicator_count} 個)")

            # ── TEST 4:抓庫柏回應內容,確認非空 ──
            try:
                last_coba = page.locator(".chat-message.coba").last
                bubble = last_coba.locator(".chat-msg-bubble")
                text = (await bubble.inner_text()).strip()
                if text and len(text) > 5:
                    results["passes"].append(f"TEST 4: 庫柏回應內容({len(text)} 字):{text[:80]}...")
                else:
                    results["fails"].append(f"TEST 4: 庫柏回應太短或空:{text!r}")
                # 確認有 AI 標籤
                has_ai_badge = await last_coba.locator(".chat-msg-coba-badge").count() > 0
                if has_ai_badge:
                    results["passes"].append("TEST 5: 庫柏訊息有「AI」標籤 ✓")
                else:
                    results["fails"].append("TEST 5: 庫柏訊息缺 AI 標籤")
            except Exception as e:
                results["fails"].append(f"TEST 4: 抓不到庫柏訊息 ({e})")

            # 最終截圖
            await page.screenshot(path=str(OUT_DIR / "coba_response.png"), full_page=False)
            print(f"截圖:{OUT_DIR}/coba_response.png")

        finally:
            await ctx.close()

        print("\n" + "=" * 60)
        print(" 測試結果")
        print("=" * 60)
        for p in results["passes"]:
            print(f"[PASS] {p}")
        for f in results["fails"]:
            print(f"[FAIL] {f}")
        print("=" * 60)
        return 0 if not results["fails"] else 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
