#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import shutil
from datetime import datetime, timezone
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
WEB_ROOT = ROOT / "apps" / "web"
DEFAULT_OUTPUT = ROOT / "dist" / "web"
ENTRYPOINTS = (
    "index.html",
    "create.html",
    "story.html",
    "design-home-desktop.html",
    "features.html",
    "pricing.html",
    "whats-new.html",
    "blog.html",
    "reviews.html",
    "install.html",
    "privacy.html",
    "delete-data.html",
    "help.html",
    "settings.html",
    "checkout.html",
    "terms.html",
    "accessibility.html",
    "contact.html",
    "gift.html",
    "press.html",
    "community.html",
    "login.html",
)
FORBIDDEN_DEPLOY_REFS = (
    "../../packages/",
    "../../tests/",
    "../../outputs/",
    "tests/fixtures/private",
    ".env",
)


def main() -> int:
    parser = argparse.ArgumentParser(description="Build the self-contained static Sixxie web site.")
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    args = parser.parse_args()

    report = build_web_static(output_dir=args.output)
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0


def build_web_static(*, output_dir: Path) -> dict[str, object]:
    if not WEB_ROOT.exists():
        raise FileNotFoundError(f"web root not found: {WEB_ROOT}")
    _validate_source_web()

    if output_dir.exists():
        shutil.rmtree(output_dir)
    output_dir.parent.mkdir(parents=True, exist_ok=True)
    shutil.copytree(WEB_ROOT, output_dir)
    _validate_built_web(output_dir)

    manifest = {
        "name": "Sixxie static web",
        "version": "0.1.0",
        "entrypoint": "index.html",
        "entrypoints": list(ENTRYPOINTS),
        "built_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
        "privacy": {
            "raw_pet_media_included": False,
            "api_keys_included": False,
            "private_fixture_paths_included": False,
        },
        "deploy": {
            "type": "static",
            "output_dir": str(output_dir.relative_to(ROOT) if output_dir.is_relative_to(ROOT) else output_dir),
        },
    }
    (output_dir / "site-manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    return {
        "ok": True,
        "output_dir": str(output_dir.relative_to(ROOT) if output_dir.is_relative_to(ROOT) else output_dir),
        "entrypoint": "index.html",
        "files": sorted(str(path.relative_to(output_dir)) for path in output_dir.rglob("*") if path.is_file()),
    }


def _validate_source_web() -> None:
    for entrypoint in ENTRYPOINTS:
        path = WEB_ROOT / entrypoint
        if not path.exists():
            raise FileNotFoundError(f"web entrypoint missing: {path}")
    for required_asset in (
        WEB_ROOT / "assets" / "brand" / "pixel-cat-logo.svg",
        WEB_ROOT / "assets" / "brand" / "sixxie-wordmark.svg",
        WEB_ROOT / "assets" / "pets" / "zhouliu" / "spritesheet.webp",
        WEB_ROOT / "assets" / "pets" / "yinengjing" / "spritesheet.webp",
    ):
        if not required_asset.exists() or required_asset.stat().st_size == 0:
            raise FileNotFoundError(f"web asset missing: {required_asset}")

    for html_path in WEB_ROOT.glob("*.html"):
        html = html_path.read_text(encoding="utf-8")
        for forbidden in FORBIDDEN_DEPLOY_REFS:
            if forbidden in html:
                raise ValueError(f"{html_path.name} contains non-deployable reference: {forbidden}")


def _validate_built_web(output_dir: Path) -> None:
    for html_path in output_dir.glob("*.html"):
        html = html_path.read_text(encoding="utf-8")
        for forbidden in FORBIDDEN_DEPLOY_REFS:
            if forbidden in html:
                raise ValueError(f"{html_path.name} contains non-deployable reference after build: {forbidden}")
    private_like = [
        path
        for path in output_dir.rglob("*")
        if path.is_file() and any(part in {"private", "raw"} for part in path.parts)
    ]
    if private_like:
        raise ValueError(f"built web contains private/raw files: {private_like[:3]}")


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