#!/usr/bin/env python3
"""
Valida uma pasta exportada de Unity WebGL para ser "publicável" em subpasta.

Requisitos mínimos (conforme seu checklist):
- web-build/index.html
- web-build/Build/ ...
- web-build/TemplateData/ ...
- ao menos 1 arquivo .wasm, .data, .js dentro de web-build/Build/

Uso:
  python3 scripts/validate_webgl_package.py --dir /abs/path/to/web-build
"""

import argparse
import re
from pathlib import Path


def any_glob_files(root: Path, pattern: str) -> list[Path]:
    return sorted(root.glob(pattern))


def must_exist(p: Path, label: str):
    if not p.exists():
        raise SystemExit(f"[FAIL] {label} missing: {p}")


def read_text_if_exists(p: Path) -> str:
    if not p.exists():
        return ""
    return p.read_text(encoding="utf-8", errors="replace")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dir", required=True, help="path da pasta web-build (ex.: /Users/.../web-build)")
    args = ap.parse_args()

    root = Path(args.dir).resolve()
    if not root.exists():
        raise SystemExit(f"[FAIL] directory not found: {root}")

    index_html = root / "index.html"
    build_dir = root / "Build"
    template_dir = root / "TemplateData"

    must_exist(index_html, "index.html")
    must_exist(build_dir, "Build/")
    must_exist(template_dir, "TemplateData/")

    wasm = any_glob_files(build_dir, "**/*.wasm")
    data = any_glob_files(build_dir, "**/*.data")
    js = any_glob_files(build_dir, "**/*.js")

    if len(wasm) < 1:
        raise SystemExit(f"[FAIL] no .wasm found under {build_dir}")
    if len(data) < 1:
        raise SystemExit(f"[FAIL] no .data found under {build_dir}")
    if len(js) < 1:
        raise SystemExit(f"[FAIL] no .js found under {build_dir}")

    # Heurística para subpasta:
    # procuramos referências relativas típicas que evitam depender de domínio raiz.
    index_text = read_text_if_exists(index_html)
    rel_build_refs_ok = bool(re.search(r'["\']\./Build/', index_text)) or bool(
        re.search(r'["\']Build/', index_text) is None
    )

    # Não é possível validar 100% sem rodar em navegador, mas deixamos um alerta.
    warnings = []
    if '"/Build/' in index_text or "'/Build/" in index_text or "Build/" in index_text:
        # Pode ser ok, mas em geral isso sugere caminho absoluto.
        # Vamos apenas alertar.
        warnings.append("index.html parece referenciar caminhos 'Build/' sem './'. Se falhar no cPanel, rode patch_webgl_index_subpath.py.")

    print("[OK] WebGL package structure looks valid.")
    print(f"- root: {root}")
    print(f"- index.html: {index_html}")
    print(f"- Build/: {build_dir} (wasm={len(wasm)}, data={len(data)}, js={len(js)})")
    print(f"- TemplateData/: {template_dir}")
    if warnings:
        for w in warnings:
            print(f"[WARN] {w}")


if __name__ == "__main__":
    main()

