#!/usr/bin/env python3
"""Fetch the current or a specific cloud-saved detail-page HTML version to local disk."""
from __future__ import annotations

import argparse
import json
import re
import sys
import urllib.parse
import urllib.request
from pathlib import Path

DEFAULT_API_BASE = "https://wwyl.yipeng.online/detail-page-api"
PROJECT_RE = re.compile(r"^[A-Za-z0-9._-]+$")


def fetch_json(url: str) -> dict:
    req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": "HermesDetailPageFetch/1.0"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode("utf-8"))


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project-id", required=True, help="Project slug, e.g. liangzhu-yuniao-gugu-v05")
    ap.add_argument("--version-id", help="Specific version id. Omit to fetch current version.")
    ap.add_argument("--api-base", default=DEFAULT_API_BASE)
    ap.add_argument("--out", type=Path, required=True, help="Output HTML path")
    args = ap.parse_args()

    if not PROJECT_RE.fullmatch(args.project_id):
        raise SystemExit("project id must contain only letters, numbers, dot, underscore, or hyphen")

    project = urllib.parse.quote(args.project_id, safe="")
    base = args.api_base.rstrip("/")
    if args.version_id:
        url = f"{base}/projects/{project}/versions/{urllib.parse.quote(args.version_id, safe='')}"
    else:
        url = f"{base}/projects/{project}/current"
    data = fetch_json(url)
    html = data.get("html")
    if not html:
        raise SystemExit(f"No html returned from {url}: {data}")
    out = args.out.expanduser().resolve()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(html, encoding="utf-8")
    print(json.dumps({
        "ok": True,
        "project_id": args.project_id,
        "version_id": data.get("version_id"),
        "out": str(out),
        "bytes": len(html.encode("utf-8")),
    }, ensure_ascii=False, indent=2))
    return 0


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