#!/usr/bin/env python3
"""Browser automation CLI using Playwright."""

import argparse
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright, Error as PlaywrightError

CHROMIUM_PATH = "/run/current-system/sw/bin/chromium"
DEFAULT_WAIT_MS = 1000


def get_browser(playwright):
    """Launch headless chromium using system binary."""
    return playwright.chromium.launch(
        executable_path=CHROMIUM_PATH,
        headless=True,
    )


def cmd_screenshot(args):
    """Capture page as PNG screenshot."""
    with sync_playwright() as p:
        browser = get_browser(p)
        page = browser.new_page()
        page.goto(args.url, wait_until="domcontentloaded")
        page.wait_for_timeout(args.wait)
        page.screenshot(path=args.output, full_page=args.full_page)
        browser.close()
    print(args.output)


def cmd_text(args):
    """Extract visible text content from page."""
    with sync_playwright() as p:
        browser = get_browser(p)
        page = browser.new_page()
        page.goto(args.url, wait_until="domcontentloaded")
        page.wait_for_timeout(args.wait)
        text = page.inner_text("body")
        browser.close()
    print(text)


def cmd_html(args):
    """Get rendered HTML after JavaScript execution."""
    with sync_playwright() as p:
        browser = get_browser(p)
        page = browser.new_page()
        page.goto(args.url, wait_until="domcontentloaded")
        page.wait_for_timeout(args.wait)
        html = page.content()
        browser.close()
    print(html)


def cmd_pdf(args):
    """Save page as PDF."""
    with sync_playwright() as p:
        browser = get_browser(p)
        page = browser.new_page()
        page.goto(args.url, wait_until="domcontentloaded")
        page.wait_for_timeout(args.wait)
        page.pdf(path=args.output)
        browser.close()
    print(args.output)


def main():
    parser = argparse.ArgumentParser(
        description="Visit web pages using Playwright browser automation"
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    # Screenshot command
    p_screenshot = subparsers.add_parser("screenshot", help="Capture page as PNG")
    p_screenshot.add_argument("url", help="URL to visit")
    p_screenshot.add_argument("output", help="Output PNG path")
    p_screenshot.add_argument(
        "--wait", type=int, default=DEFAULT_WAIT_MS, help="Wait after load (ms)"
    )
    p_screenshot.add_argument(
        "--full-page", action="store_true", help="Capture full scrollable page"
    )
    p_screenshot.set_defaults(func=cmd_screenshot)

    # Text command
    p_text = subparsers.add_parser("text", help="Extract visible text content")
    p_text.add_argument("url", help="URL to visit")
    p_text.add_argument("--wait", type=int, default=DEFAULT_WAIT_MS, help="Wait after load (ms)")
    p_text.set_defaults(func=cmd_text)

    # HTML command
    p_html = subparsers.add_parser("html", help="Get rendered HTML")
    p_html.add_argument("url", help="URL to visit")
    p_html.add_argument("--wait", type=int, default=DEFAULT_WAIT_MS, help="Wait after load (ms)")
    p_html.set_defaults(func=cmd_html)

    # PDF command
    p_pdf = subparsers.add_parser("pdf", help="Save page as PDF")
    p_pdf.add_argument("url", help="URL to visit")
    p_pdf.add_argument("output", help="Output PDF path")
    p_pdf.add_argument("--wait", type=int, default=DEFAULT_WAIT_MS, help="Wait after load (ms)")
    p_pdf.set_defaults(func=cmd_pdf)

    args = parser.parse_args()

    # Check chromium exists
    if not Path(CHROMIUM_PATH).exists():
        print(f"Error: Chromium not found at {CHROMIUM_PATH}", file=sys.stderr)
        sys.exit(1)

    try:
        args.func(args)
    except PlaywrightError as e:
        print(f"Browser error: {e}", file=sys.stderr)
        sys.exit(1)
    except OSError as e:
        print(f"File error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
