"""Automated Playwright browser test for AI Agent Budget & Token Usage tracking."""

import asyncio
import os
import sys
from pathlib import Path

from playwright.async_api import async_playwright

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

BASE_URL = os.environ.get("TEST_BASE_URL", "http://127.0.0.1:8000")
SCREENSHOT_DIR = Path("reports/screenshots")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)


async def run():
    print(
        f"[TEST] Starting AI Budget UI Playwright verification on {BASE_URL}...",
        flush=True,
    )
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={"width": 1440, "height": 900},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 DSConsE2E",
        )
        page = await context.new_page()

        # Step 1: Login
        print("[TEST 1/5] Logging in as SuperAdmin...", flush=True)
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.click("button:has-text('SuperAdmin')")
        await page.wait_for_url("**/dashboard", timeout=10000)
        await page.wait_for_timeout(1000)
        print(f"  -> Landed on URL: {page.url}", flush=True)

        # Step 2: AI Chat section & Live Budget Tracker Bar
        print(
            "[TEST 2/5] Verifying AI Chat section & Live Budget Tracker Bar...",
            flush=True,
        )
        chat_section = await page.wait_for_selector("#ai-chat-section", timeout=5000)
        await page.evaluate(
            "document.getElementById('ai-chat-section').scrollIntoView()"
        )
        await page.wait_for_timeout(1000)

        # Verify 4 period buttons
        period_tabs = await page.query_selector_all(
            "#budget-period-tabs .budget-period-btn"
        )
        print(
            f"  -> Found {len(period_tabs)} period buttons (Day/Week/Month/Year).",
            flush=True,
        )
        assert len(period_tabs) == 4, (
            f"Expected 4 period buttons, got {len(period_tabs)}"
        )

        # Initial metrics
        spent_el = await page.query_selector("#agent-budget-spent")
        total_el = await page.query_selector("#agent-budget-total")
        pct_el = await page.query_selector("#agent-budget-pct-badge")
        tokens_el = await page.query_selector("#agent-budget-tokens")

        spent_text = await spent_el.inner_text()
        total_text = await total_el.inner_text()
        pct_text = await pct_el.inner_text()
        tokens_text = await tokens_el.inner_text()
        print(
            f"  -> Initial [Minh - Day]: Spent={spent_text}, Total={total_text}, Pct={pct_text}, Tokens={tokens_text}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "ai_budget_01_initial_day.png"))

        # Step 3: Switch time period tabs (Tuần, Tháng, Năm)
        print(
            "[TEST 3/5] Testing period tab switching (Tuần -> Tháng -> Năm)...",
            flush=True,
        )
        await page.click('button[data-period="week"]')
        await page.wait_for_timeout(400)
        print(
            f"  -> [Minh - Tuần]: Spent={await spent_el.inner_text()}, Total={await total_el.inner_text()}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "ai_budget_02_week.png"))

        await page.click('button[data-period="month"]')
        await page.wait_for_timeout(400)
        print(
            f"  -> [Minh - Tháng]: Spent={await spent_el.inner_text()}, Total={await total_el.inner_text()}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "ai_budget_03_month.png"))

        await page.click('button[data-period="year"]')
        await page.wait_for_timeout(400)
        print(
            f"  -> [Minh - Năm]: Spent={await spent_el.inner_text()}, Total={await total_el.inner_text()}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "ai_budget_04_year.png"))

        # Switch back to 'Ngày'
        await page.click('button[data-period="day"]')
        await page.wait_for_timeout(300)

        # Step 4: Test Agent Dropdown change & Sidebar mini overview
        print(
            "[TEST 4/5] Testing Agent selector change and sidebar list...", flush=True
        )
        await page.select_option("#chat-agent-select", "tung")
        await page.wait_for_timeout(400)
        agent_name_el = await page.query_selector("#current-agent-name")
        agent_name = await agent_name_el.inner_text()
        print(f"  -> Active agent switched to: {agent_name}", flush=True)
        assert "Tùng" in agent_name

        # Verify sidebar 9 agents list
        sidebar_items = await page.query_selector_all(
            "#sidebar-agents-budget-list > div"
        )
        print(
            f"  -> Found {len(sidebar_items)} AI agents in sidebar budget overview.",
            flush=True,
        )
        assert len(sidebar_items) >= 9

        # Click on 'quynh' in sidebar list
        await page.evaluate("selectAgentByCode('quynh')")
        await page.wait_for_timeout(400)
        agent_name_quynh = await agent_name_el.inner_text()
        print(f"  -> Switched via sidebar click to: {agent_name_quynh}", flush=True)
        assert "Quỳnh" in agent_name_quynh
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "ai_budget_05_agent_switch.png")
        )

        # Step 5: Send chat message and verify live budget update
        print(
            "[TEST 5/5] Sending chat message to verify live token calculation...",
            flush=True,
        )
        await page.fill(
            "#chat-input-text",
            "Kiểm tra dòng tiền tạm ứng đợt 1 Ban QLDA xã Kiến Minh 2026",
        )
        await page.click("#chat-send-btn")

        # Wait for AI response message
        await page.wait_for_timeout(3000)

        updated_spent = await spent_el.inner_text()
        updated_tokens = await tokens_el.inner_text()
        print(
            f"  -> Live Updated Metrics (Quỳnh): Spent={updated_spent}, Tokens={updated_tokens}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "ai_budget_06_after_chat.png"))

        await browser.close()
        print("[SUCCESS] All AI Budget browser E2E tests PASSED 100%!", flush=True)


if __name__ == "__main__":
    asyncio.run(run())
