#!/usr/bin/env python3
import argparse
import os
import json
import sys

from playwright.sync_api import sync_playwright


def main() -> int:
    ap = argparse.ArgumentParser(description="Headless screenshot helper for MC UI (Playwright).")
    ap.add_argument("--url", required=True, help="Full URL to capture (e.g. http://localhost:19100/credentials)")
    ap.add_argument("--token", required=True, help="MC bearer token stored as localStorage mc_token")
    ap.add_argument("--out", required=True, help="Output path for screenshot PNG")
    ap.add_argument("--width", type=int, default=1400)
    ap.add_argument("--height", type=int, default=900)
    ap.add_argument("--full-page", action="store_true", help="Capture full scroll height")
    args = ap.parse_args()

    out_dir = os.path.dirname(os.path.abspath(args.out)) or "."
    os.makedirs(out_dir, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            viewport={"width": args.width, "height": args.height},
        )
        context.add_init_script(f"localStorage.setItem('mc_token', {json.dumps(args.token)});")
        page = context.new_page()
        page.goto(args.url, wait_until="domcontentloaded")
        page.wait_for_load_state("networkidle")
        page.wait_for_timeout(250)
        page.screenshot(path=args.out, full_page=args.full_page)
        context.close()
        browser.close()

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
