#!/usr/bin/env python3
"""
capture-revolut-live.py
Capture live Revolut screenshots using playwright-stealth to bypass Cloudflare.
Usage: python3 scripts/capture-revolut-live.py [--output-dir <dir>]
"""

import asyncio
import sys
import os
import argparse
from pathlib import Path
from playwright.async_api import async_playwright
from playwright_stealth import Stealth

OUTPUT_DIR = Path('/root/.openclaw/workspace/public/etoro-competition/revolut/assets')

UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'

CAPTURES = [
    {
        'name': 'live-homepage-hero',
        'url': 'https://www.revolut.com',
        'wait': 4000,
        'clip': {'x': 0, 'y': 0, 'width': 1440, 'height': 900},
        'desc': 'Homepage above the fold'
    },
    {
        'name': 'live-homepage-full',
        'url': 'https://www.revolut.com',
        'wait': 5000,
        'full_page': True,
        'scroll': True,
        'desc': 'Homepage full page (lazy-load triggered)'
    },
    {
        'name': 'live-premium-cards',
        'url': 'https://www.revolut.com/cards',
        'wait': 4000,
        'clip': {'x': 0, 'y': 0, 'width': 1440, 'height': 900},
        'desc': 'Cards/premium page hero'
    },
    {
        'name': 'live-premium-cards-full',
        'url': 'https://www.revolut.com/cards',
        'wait': 5000,
        'full_page': True,
        'scroll': True,
        'desc': 'Cards page full'
    },
    {
        'name': 'live-ultra',
        'url': 'https://www.revolut.com/ultra',
        'wait': 4000,
        'clip': {'x': 0, 'y': 0, 'width': 1440, 'height': 900},
        'desc': 'Ultra tier page'
    },
    {
        'name': 'live-features',
        'url': 'https://www.revolut.com/features',
        'wait': 4000,
        'clip': {'x': 0, 'y': 0, 'width': 1440, 'height': 900},
        'desc': 'Features page'
    },
    {
        'name': 'live-business',
        'url': 'https://www.revolut.com/business',
        'wait': 4000,
        'clip': {'x': 0, 'y': 0, 'width': 1440, 'height': 900},
        'desc': 'Business page'
    },
]

async def dismiss_banners(page):
    try:
        await page.evaluate("""() => {
            document.querySelectorAll(
                '[class*=cookie],[id*=cookie],[class*=banner],[class*=consent],'+
                '[class*=modal],[class*=overlay],[class*=popup],[class*=gdpr],[id*=gdpr],'+
                '[class*=notice],[class*=CookieConsent],[id*=CookieBanner]'
            ).forEach(el => el.remove());
            document.body && (document.body.style.overflow = 'auto');
        }""")
    except Exception:
        pass

async def scroll_page(page):
    """Scroll down to trigger lazy-load, then back to top."""
    try:
        await page.evaluate("""async () => {
            await new Promise(resolve => {
                let total = 0;
                const step = 600;
                const timer = setInterval(() => {
                    window.scrollBy(0, step);
                    total += step;
                    if (total >= document.body.scrollHeight) {
                        clearInterval(timer);
                        window.scrollTo(0, 0);
                        resolve();
                    }
                }, 200);
            });
        }""")
        await page.wait_for_timeout(1500)
    except Exception:
        pass

async def capture(browser, stealth_obj, spec, output_dir):
    context = await browser.new_context(
        viewport={'width': 1440, 'height': 900},
        user_agent=UA,
        locale='en-GB',
        timezone_id='Europe/London',
        extra_http_headers={'Accept-Language': 'en-GB,en;q=0.9'}
    )
    page = await context.new_page()
    await stealth_obj.apply_stealth_async(page)

    name = spec['name']
    print(f'  [{name}] {spec["desc"]}...')

    try:
        await page.goto(spec['url'], wait_until='domcontentloaded', timeout=30000)
        await page.wait_for_timeout(spec.get('wait', 3000))
        await dismiss_banners(page)

        content = await page.content()
        if 'cloudflare' in content.lower() and ('challenge' in content.lower() or 'ray id' in content.lower()):
            print(f'  [{name}] ⚠ Cloudflare block detected — skipping')
            await context.close()
            return False

        if spec.get('scroll'):
            await scroll_page(page)

        out_path = output_dir / f'{name}.png'
        if spec.get('full_page'):
            await page.screenshot(path=str(out_path), full_page=True)
        elif spec.get('clip'):
            await page.screenshot(path=str(out_path), clip=spec['clip'])
        else:
            await page.screenshot(path=str(out_path))

        size = out_path.stat().st_size
        print(f'  [{name}] ✅ Saved ({size/1024:.0f}KB) → {out_path.name}')
        await context.close()
        return True

    except Exception as e:
        print(f'  [{name}] ❌ Error: {e}')
        await context.close()
        return False

async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--output-dir', default=str(OUTPUT_DIR))
    parser.add_argument('--urls', nargs='*', help='Capture specific URLs (name:url format)')
    args = parser.parse_args()

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    stealth_obj = Stealth(navigator_webdriver=True)

    captures = CAPTURES
    if args.urls:
        captures = []
        for u in args.urls:
            if ':' in u:
                name, url = u.split(':', 1)
            else:
                name = 'custom-' + str(len(captures))
                url = u
            captures.append({'name': name, 'url': url, 'wait': 4000, 'desc': url})

    print(f'Output dir: {output_dir}')
    print(f'Capturing {len(captures)} pages...\n')

    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=[
                '--no-sandbox',
                '--disable-blink-features=AutomationControlled',
                '--disable-dev-shm-usage',
            ]
        )

        results = []
        for spec in captures:
            ok = await capture(browser, stealth_obj, spec, output_dir)
            results.append((spec['name'], ok))
            await asyncio.sleep(1)  # rate limit between requests

        await browser.close()

    print(f'\n{"="*40}')
    ok_count = sum(1 for _, ok in results if ok)
    print(f'Done: {ok_count}/{len(results)} captured')
    for name, ok in results:
        print(f'  {"✅" if ok else "❌"} {name}')

if __name__ == '__main__':
    asyncio.run(main())
