"""
Targeted screenshot script for feature verification.
Captures specific pages into tmp/feature-review/after/
"""
import asyncio
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 / "after"
OUT_DIR.mkdir(parents=True, exist_ok=True)


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 main():
    results = []
    errors = []

    async with async_playwright() as pw:
        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)

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

        print(f"Logged in, at: {page.url}")

        # -- login.png: logged-out page --
        print("Shooting login page (logged out)...")
        ctx2 = await browser.new_context(viewport={"width": 1440, "height": 900})
        page2 = await ctx2.new_page()
        await page2.goto(f"{BASE_URL}/login")
        await wait_for_page(page2)
        await page2.screenshot(path=str(OUT_DIR / "login.png"), full_page=True)
        dims = await page2.evaluate("() => ({ w: document.body.scrollWidth, h: document.body.scrollHeight })")
        results.append(f"login.png: {dims['w']}x{dims['h']}px")
        await ctx2.close()

        # Pages to shoot (full-page)
        full_page_shots = [
            ("/guides", "guides.png"),
            ("/orders?sort=amount_desc", "orders.png"),
            ("/dashboard", "dashboard.png"),
            ("/settings", "settings.png"),
            ("/ticket/101", "ticket-101.png"),
        ]

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

                if "/login" in page.url:
                    errors.append(f"{filename}: redirected to login")
                    continue

                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", "BuildError"])

                await page.screenshot(path=str(OUT_DIR / filename), full_page=True)
                dims = await page.evaluate("() => ({ w: document.body.scrollWidth, h: document.body.scrollHeight })")
                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 in body")
            except Exception as e:
                errors.append(f"{filename}: exception - {e}")

        # ratings.png — viewport only (page is 43k px tall)
        print("Shooting /ratings -> ratings.png (viewport only)...")
        try:
            await page.goto(f"{BASE_URL}/ratings")
            await wait_for_page(page)
            if "/login" in page.url:
                errors.append("ratings.png: redirected to login")
            else:
                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"])
                await page.screenshot(path=str(OUT_DIR / "ratings.png"), full_page=False)
                dims = await page.evaluate("() => ({ w: window.innerWidth, h: window.innerHeight })")
                status = "ERROR" if is_error else "ok (viewport)"
                results.append(f"ratings.png: {dims['w']}x{dims['h']}px [{status}]")
        except Exception as e:
            errors.append(f"ratings.png: exception - {e}")

        # Try to get a real product ID for guides-filtered.png
        print("Looking for a product ID for guides-filtered.png...")
        try:
            await page.goto(f"{BASE_URL}/products")
            await wait_for_page(page)
            # Try to find a product link
            links = await page.eval_on_selector_all(
                'a[href*="/products/"]',
                'els => els.map(e => e.getAttribute("href"))'
            )
            product_id = None
            import re
            for link in links:
                m = re.match(r'^/products/(\d+)', link or '')
                if m:
                    product_id = m.group(1)
                    break

            if product_id:
                print(f"Found product ID: {product_id}, shooting guides-filtered.png")
                await page.goto(f"{BASE_URL}/guides?product={product_id}")
                await wait_for_page(page)
                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", "BuildError"])
                await page.screenshot(path=str(OUT_DIR / "guides-filtered.png"), full_page=True)
                dims = await page.evaluate("() => ({ w: document.body.scrollWidth, h: document.body.scrollHeight })")
                status = "ERROR" if is_error else "ok"
                results.append(f"guides-filtered.png (product={product_id}): {dims['w']}x{dims['h']}px [{status}]")
            else:
                errors.append("guides-filtered.png: no product link found on /products page")
        except Exception as e:
            errors.append(f"guides-filtered.png: exception - {e}")

        await 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)
