"""Ticket 06 browser verification against deployed t480 frontend.

Logs in, opens the E2E campaign report drawer, checks the 探索发现 section,
expands the session, and screenshots each stage.
"""

import sys

from playwright.sync_api import sync_playwright

BASE = "http://192.168.8.145:8001"
CAMPAIGN = "巡检E2E-正式线种子演示"
SHOTS = "/tmp/ticket06"


def main():
    token = sys.argv[1]
    import os

    os.makedirs(SHOTS, exist_ok=True)
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": 1600, "height": 1000})
        page.add_init_script(f"sessionStorage.setItem('agenteval_auth_token', '{token}')")

        page.goto(BASE + "/campaigns", wait_until="networkidle")
        page.screenshot(path=f"{SHOTS}/01-home.png")
        page.wait_for_selector(f"text={CAMPAIGN}", timeout=10000)
        page.screenshot(path=f"{SHOTS}/02-campaigns.png")

        row = page.locator("tr", has_text=CAMPAIGN)
        row.get_by_role("button", name="报告").click()
        page.wait_for_selector("text=探索发现", timeout=15000)
        page.wait_for_selector("text=探索会话 1 个", timeout=10000)
        page.wait_for_selector("text=发送用户消息后API一直超时无响应", timeout=10000)
        page.wait_for_selector("text=judge 复核", timeout=10000)
        page.wait_for_timeout(1000)
        page.screenshot(path=f"{SHOTS}/03-drawer.png", full_page=True)

        header = page.locator(".ant-collapse-header", has_text="有点急性子的用户")
        header.click()
        page.wait_for_selector("text=体验记录", timeout=10000)
        page.wait_for_selector("text=询问医院基本信息", timeout=10000)
        page.wait_for_timeout(1500)
        page.screenshot(path=f"{SHOTS}/04-session-expanded.png", full_page=True)

        panel = page.locator(".ant-collapse-content-active")
        if not panel.count():
            panel = page.locator(".ant-collapse-item-active")
        bubbles = panel.first.inner_text()
        checks = {
            "用户气泡": "用户" in bubbles or len(bubbles) > 50,
            "目标未达成标签": "未达成" in bubbles or "否" in bubbles,
            "情绪标签": "neutral" in bubbles or "平静" in bubbles,
            "障碍文本": "超时" in bubbles,
        }
        for k, v in checks.items():
            print(f"CHECK {k}: {'PASS' if v else 'FAIL'}")
        print("SNIPPET:", bubbles[:400].replace("\n", " | "))
        browser.close()


if __name__ == "__main__":
    main()
