#!/usr/bin/env python3
"""Enable an exact Cloudflare Pages origin to call the local H3 Studio API."""

from __future__ import annotations

import argparse
import json
import secrets
from pathlib import Path
from urllib.parse import urlparse


ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "studio" / "cloud_access.json"


def parse_origin(value: str) -> str:
    origin = value.strip().rstrip("/")
    parsed = urlparse(origin)
    if parsed.scheme != "https" or not parsed.netloc or parsed.path not in {"", "/"}:
        raise argparse.ArgumentTypeError("origin 必须是纯 HTTPS 来源，例如 https://my-h3.pages.dev")
    return f"https://{parsed.netloc}"


def load() -> dict:
    if not CONFIG.is_file():
        return {}
    try:
        value = json.loads(CONFIG.read_text(encoding="utf-8"))
        return value if isinstance(value, dict) else {}
    except (OSError, json.JSONDecodeError):
        return {}


def main() -> int:
    parser = argparse.ArgumentParser(description="Configure Cloudflare Pages access to local H3 Studio")
    parser.add_argument("--origin", required=True, type=parse_origin, help="Exact Pages/custom-domain origin")
    parser.add_argument("--disable", action="store_true", help="Disable remote browser access")
    args = parser.parse_args()
    value = load()
    origins = {str(item).rstrip("/") for item in value.get("allowed_origins", []) if str(item).startswith("https://")}
    origins.add(args.origin)
    value = {
        "version": 1,
        "enabled": not args.disable,
        "access_key": str(value.get("access_key") or secrets.token_urlsafe(32)),
        "allowed_origins": sorted(origins),
    }
    CONFIG.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({
        "enabled": value["enabled"],
        "origin": args.origin,
        "access_key": value["access_key"],
        "config": str(CONFIG),
    }, ensure_ascii=False, indent=2))
    return 0


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