"""Create a source-only cPanel ZIP without workstation secrets or binaries."""
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import datetime, timezone
import hashlib
import json

root = Path(__file__).resolve().parent.parent
destination = root.parent / "mbg-cpanel-upload.zip"
top_files = ["app.js", "package.json", "package-lock.json", "next.config.ts",
             "tsconfig.json", "README.md", ".env.cpanel.example"]
folders = ["src", "public", "database", "scripts", "tests"]
files = [root / name for name in top_files]
for folder in folders:
    files.extend(file for file in (root / folder).rglob("*") if file.is_file())
files = sorted(set(files))
for file in files:
    relative = file.relative_to(root)
    if file.is_symlink() or any(part in {".local", ".git", "node_modules", ".next", "__pycache__"} for part in relative.parts):
        raise RuntimeError("Unexpected private or generated file in source package")
    if relative.name.startswith(".env") and relative.name != ".env.cpanel.example":
        raise RuntimeError("Only the placeholder cPanel environment template may be included")
    if file.suffix == ".sql" and relative.as_posix() != "database/schema.sql":
        raise RuntimeError("Database exports must not be included in a web upload package")
    if not file.is_file():
        raise RuntimeError("Required source file is missing")

metadata = {
    "format": 1,
    "target": "cpanel-node-passenger",
    "createdAt": datetime.now(timezone.utc).isoformat(),
    "buildOnHost": True,
    "databaseIncluded": False,
    "secretsIncluded": False,
    "files": {file.relative_to(root).as_posix(): hashlib.sha256(file.read_bytes()).hexdigest() for file in files},
}
with ZipFile(destination, "w", compression=ZIP_DEFLATED, compresslevel=9) as archive:
    for file in files:
        archive.write(file, "mbg-cpanel/" + file.relative_to(root).as_posix())
    archive.writestr("mbg-cpanel/cpanel-package.json", json.dumps(metadata, indent=2) + "\n")

with ZipFile(destination) as archive:
    if archive.testzip() is not None:
        raise RuntimeError("ZIP integrity verification failed")
    names = archive.namelist()
    for name in top_files:
        assert "mbg-cpanel/" + name in names
    for file, expected in metadata["files"].items():
        assert hashlib.sha256(archive.read("mbg-cpanel/" + file)).hexdigest() == expected

digest = hashlib.sha256(destination.read_bytes()).hexdigest()
print(f"Created: {destination}")
print(f"Files: {len(names)}; size: {destination.stat().st_size:,} bytes")
print(f"SHA256: {digest}")
print("Archive contents and integrity verified. No credentials, database export, node_modules or workstation build included.")
