"""
Full-page screenshot script for ModuleDesk app review.
Captures all main pages logged in as admin@local.test.
"""
import asyncio
import re
import sys
from pathlib import Path
from playwright.async_api import async_playwright

BASE_URL = "http://127.0.0.1:5000"
EMAIL = "admin@local.test"
PASSWORD = "Admin123!ChangeMe"
OUT_DIR = Path(__file__).parent
OUT_DIR.mkdir(parents=True, exist_ok=True)

PAGES = [
    ("/dashboard", "dashboard.png"),
    ("/inbox", "inbox.png"),
    ("/ticket/101", "ticket-101.png"),
    ("/customers", "customers.png"),
    ("/orders", "orders.png"),
    ("/products", "products.png"),
    ("/ratings", "ratings.png"),
    ("/ratings/import", "ratings-import.png"),
    ("/guides", "guides.png"),
    ("/predefined-messages", "predefined-messages.png"),
    ("/search?q=invoice", "search.png"),
    ("/settings", "settings.png"),
    ("/settings/billing", "settings-billing.png"),
    ("/settings/team", "settings-team.png"),
]

MOBILE_PAGES = [
    ("/inbox", "inbox-mobile.png"),
    ("/ticket/101", "ticket-101-mobile.png"),
]


async def wait_for_page(page, timeout=8000):
    try:
        await page.wait_for_load_state("networkidle", timeout=timeout)
    except Exception:
        await page.wait_for_timeout(2000)


async def screenshot_page(page, path, full_page=True):
    await page.screenshot(path=str(path), full_page=full_page)
    # Return pixel height
    dims = await page.evaluate("() => ({ w: document.body.scrollWidth, h: document.body.scrollHeight })")
    return dims


async def main():
    results = []
    errors = []

    async with async_playwright() as pw:
        # --- Desktop browser ---
        browser = await pw.chromium.launch(headless=True)
        ctx = await browser.new_context(
            viewport={"width": 1440, "height": 900},
            device_scale_factor=1,
        )
        page = await ctx.new_page()

        # Login
        print("Logging in...")
        await page.goto(f"{BASE_URL}/login")
        await wait_for_page(page)
        await page.fill('input[name="username"]', EMAIL)
        await page.fill('input[name="password"]', PASSWORD)
        await page.click('button[type="submit"]')
        await wait_for_page(page)

        current_url = page.url
        if "/login" in current_url:
            print("ERROR: Login failed, still on login page")
            errors.append("LOGIN FAILED")
            await browser.close()
            return results, errors

        print(f"Logged in, now at: {current_url}")

        # Find first customer detail URL
        customer_detail_url = None
        print("Fetching /customers to find first customer link...")
        await page.goto(f"{BASE_URL}/customers")
        await wait_for_page(page)
        links = await page.eval_on_selector_all(
            'a[href*="/customers/"]',
            'els => els.map(e => e.getAttribute("href"))'
        )
        for link in links:
            if link and re.match(r'^/customers/[a-f0-9]+', link):
                customer_detail_url = link
                break
        if customer_detail_url:
            print(f"Found customer detail: {customer_detail_url}")
        else:
            print("WARNING: No customer detail link found")

        # Screenshot all desktop pages
        pages_to_shoot = list(PAGES)
        if customer_detail_url:
            pages_to_shoot.insert(4, (customer_detail_url, "customer-detail.png"))
        else:
            errors.append("customer-detail.png: no customer link found")

        for url, filename in pages_to_shoot:
            full_url = f"{BASE_URL}{url}" if url.startswith("/") else f"{BASE_URL}{url}"
            print(f"Shooting {url} -> {filename}")
            try:
                await page.goto(full_url)
                await wait_for_page(page)

                # Check if redirected to login
                if "/login" in page.url:
                    errors.append(f"{filename}: redirected to login (auth lost)")
                    await page.screenshot(path=str(OUT_DIR / filename), full_page=True)
                    results.append(f"{filename}: redirected to login")
                    continue

                # Check for server error
                title = await page.title()
                body_text = await page.evaluate("() => document.body ? document.body.innerText.substring(0, 200) : ''")
                is_error = any(x in body_text for x in ["Internal Server Error", "500", "Traceback", "raise "])

                dims = await screenshot_page(page, OUT_DIR / filename)
                status = "ERROR" if is_error else "ok"
                results.append(f"{filename}: {dims['w']}x{dims['h']}px [{status}]")
                if is_error:
                    errors.append(f"{filename}: server error detected in body")
            except Exception as e:
                errors.append(f"{filename}: exception - {e}")
                print(f"  EXCEPTION: {e}")

        await ctx.close()

        # --- Mobile browser ---
        print("\nSwitching to mobile viewport (390x844)...")
        mobile_ctx = await browser.new_context(
            viewport={"width": 390, "height": 844},
            device_scale_factor=2,
        )
        mpage = await mobile_ctx.new_page()

        # Login again for mobile context
        await mpage.goto(f"{BASE_URL}/login")
        await wait_for_page(mpage)
        await mpage.fill('input[name="username"]', EMAIL)
        await mpage.fill('input[name="password"]', PASSWORD)
        await mpage.click('button[type="submit"]')
        await wait_for_page(mpage)

        for url, filename in MOBILE_PAGES:
            print(f"Mobile shot {url} -> {filename}")
            try:
                await mpage.goto(f"{BASE_URL}{url}")
                await wait_for_page(mpage)
                dims = await screenshot_page(mpage, OUT_DIR / filename)
                results.append(f"{filename}: {dims['w']}x{dims['h']}px [mobile]")
            except Exception as e:
                errors.append(f"{filename}: mobile exception - {e}")

        await mobile_ctx.close()
        await browser.close()

    return results, errors


if __name__ == "__main__":
    results, errors = asyncio.run(main())
    print("\n=== FILES WRITTEN ===")
    for r in results:
        print(r)
    if errors:
        print("\n=== ERRORS / WARNINGS ===")
        for e in errors:
            print(e)
    sys.exit(0)
