"""
SEC EDGAR HTML to PDF converter.
Uses Playwright + Chrome to render filings with images.

Usage:
    python sec_to_pdf.py <filing_url> <output_path>

Example:
    python sec_to_pdf.py "https://www.sec.gov/Archives/edgar/data/320193/000032019324000123/aapl-20240928.htm" "/workspace/aapl_10k.pdf"

Why Chrome?
    SEC.gov blocks headless Chromium with 403 errors (bot detection).
    Using channel='chrome' with Playwright uses real Google Chrome which bypasses this.
"""

import asyncio
import os
import sys

from playwright.async_api import async_playwright


async def convert_sec_filing_to_pdf(url: str, output_path: str) -> dict:
    """
    Convert SEC EDGAR filing to PDF with images.

    Args:
        url: Full URL to SEC filing HTML
        output_path: Where to save the PDF

    Returns:
        dict with status, pdf_size, and image_count
    """
    async with async_playwright() as p:
        # MUST use channel='chrome' - regular Chromium gets 403 blocked by SEC
        browser = await p.chromium.launch(headless=True, channel='chrome')
        context = await browser.new_context(user_agent='ShortcutAgent/1.0 (support@shortcut.ai)')
        page = await context.new_page()

        # Navigate to filing (networkidle waits for no network activity for 500ms)
        response = await page.goto(url, wait_until='networkidle', timeout=20000)

        if response is None or response.status != 200:
            await browser.close()
            return {
                'status': 'error',
                'code': response.status if response else 0,
                'message': 'SEC blocked request or navigation failed',
            }

        # Count images for verification
        images = await page.query_selector_all('img')
        image_count = len(images)

        # Generate PDF
        pdf_bytes = await page.pdf(format='A4', print_background=True)

        # Ensure output directory exists and save
        output_dir = os.path.dirname(output_path)
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)
        with open(output_path, 'wb') as f:
            f.write(pdf_bytes)

        await browser.close()

        return {
            'status': 'success',
            'pdf_path': output_path,
            'pdf_size_bytes': len(pdf_bytes),
            'image_count': image_count,
        }


async def main():
    if len(sys.argv) != 3:
        print('Usage: python sec_to_pdf.py <filing_url> <output_path>')
        print()
        print('Example:')
        print(
            '  python sec_to_pdf.py "https://www.sec.gov/Archives/edgar/data/320193/000032019324000123/aapl-20240928.htm" "/workspace/aapl_10k.pdf"'
        )
        sys.exit(1)

    url = sys.argv[1]
    output_path = sys.argv[2]

    print('Converting SEC filing to PDF...')
    print(f'  URL: {url}')
    print(f'  Output: {output_path}')
    print()

    result = await convert_sec_filing_to_pdf(url, output_path)

    if result['status'] == 'success':
        size_mb = result['pdf_size_bytes'] / (1024 * 1024)
        print('Success!')
        print(f'  PDF saved to: {result["pdf_path"]}')
        print(f'  PDF size: {result["pdf_size_bytes"]:,} bytes ({size_mb:.2f} MB)')
        print(f'  Images rendered: {result["image_count"]}')
    else:
        print(f'Error: {result["message"]} (code: {result["code"]})')
        sys.exit(1)


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