"""
Additional competitive pages + retry IsOn24 homepage
"""
import os
import time
import json
from playwright.sync_api import sync_playwright

OUTPUT_DIR = "/mnt/e/genesis-system/qa_reports/competitive_screenshots"

PAGES = [
    # IsOn24 retry with domcontentloaded
    {"url": "https://www.ison24.com", "name": "ison24_home", "label": "IsOn24 - Homepage", "wait": "domcontentloaded"},
    # ClawdTalk - explore other nav links
    {"url": "https://clawdtalk.com/#features", "name": "clawdtalk_features", "label": "ClawdTalk - Features section", "wait": "load"},
    # OpenClaw additional pages
    {"url": "https://www.getopenclaw.ai/features", "name": "openclaw_features", "label": "OpenClaw - Features", "wait": "networkidle"},
    {"url": "https://www.getopenclaw.ai/signup", "name": "openclaw_signup", "label": "OpenClaw - Signup", "wait": "networkidle"},
    # Mitra
    {"url": "https://www.getmitra.com/how-it-works", "name": "mitra_how", "label": "Mitra - How it works", "wait": "networkidle"},
    {"url": "https://www.getmitra.com/demo", "name": "mitra_demo", "label": "Mitra - Demo", "wait": "networkidle"},
]

results = []

def capture_page(page, url, name, label, wait_until="networkidle"):
    print(f"\n--- Capturing: {label} ---")
    try:
        page.goto(url, wait_until=wait_until, timeout=25000)
        time.sleep(2)

        screenshot_path = os.path.join(OUTPUT_DIR, f"{name}_full.png")
        page.screenshot(path=screenshot_path, full_page=True)

        title = page.title()
        dims = page.evaluate("() => ({w: document.body.scrollWidth, h: document.body.scrollHeight})")

        text = page.evaluate("""() => {
            const els = document.querySelectorAll('h1, h2, h3, h4, p, li, button, a, span');
            return Array.from(els).map(el => el.innerText?.trim()).filter(t => t && t.length > 3).slice(0, 200);
        }""")

        links = page.evaluate("""() => {
            return Array.from(document.querySelectorAll('a[href]')).map(a => ({
                text: a.innerText?.trim(),
                href: a.href
            })).filter(l => l.text && l.text.length > 1).slice(0, 50);
        }""")

        print(f"  OK: {title} | {dims}")
        return {
            "name": name, "label": label, "url": url, "title": title,
            "dimensions": dims, "screenshot": screenshot_path,
            "text_content": text, "links": links, "success": True, "error": None
        }
    except Exception as e:
        print(f"  FAIL: {e}")
        try:
            page.screenshot(path=os.path.join(OUTPUT_DIR, f"{name}_partial.png"), full_page=False)
            title = page.title()
            dims = page.evaluate("() => ({w: document.body.scrollWidth, h: document.body.scrollHeight})")
            text = page.evaluate("""() => {
                const els = document.querySelectorAll('h1, h2, h3, h4, p, li, button, a, span');
                return Array.from(els).map(el => el.innerText?.trim()).filter(t => t && t.length > 3).slice(0, 200);
            }""")
            links = page.evaluate("""() => {
                return Array.from(document.querySelectorAll('a[href]')).map(a => ({
                    text: a.innerText?.trim(), href: a.href
                })).filter(l => l.text && l.text.length > 1).slice(0, 50);
            }""")
            print(f"  Partial: {title}")
            return {
                "name": name, "label": label, "url": url, "title": title,
                "dimensions": dims, "screenshot": os.path.join(OUTPUT_DIR, f"{name}_partial.png"),
                "text_content": text, "links": links, "success": True, "error": f"Timeout but partial: {str(e)[:100]}"
            }
        except Exception as e2:
            return {"name": name, "label": label, "url": url, "success": False, "error": str(e)[:100]}


with sync_playwright() as p:
    browser = p.chromium.launch(headless=True, args=['--no-sandbox', '--disable-dev-shm-usage'])
    context = 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"
    )
    page = context.new_page()

    for p_config in PAGES:
        result = capture_page(page, p_config["url"], p_config["name"], p_config["label"], p_config.get("wait", "networkidle"))
        results.append(result)
        time.sleep(1)

    browser.close()

summary_path = os.path.join(OUTPUT_DIR, "capture_results_additional.json")
with open(summary_path, 'w') as f:
    json.dump(results, f, indent=2)

print("\n=== ADDITIONAL CAPTURE COMPLETE ===")
for r in results:
    status = "OK" if r.get('success') else f"FAIL: {r.get('error','')[:60]}"
    print(f"  {r['label']}: {status}")
