"""Check release packaging rules so full source zips keep nexaoffice_worksuite/."""
from __future__ import annotations

import json
import re
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPORT_PATH = ROOT / "data" / "package_structure_latest.json"


def _version() -> str:
    text = (ROOT / "core" / "constants.py").read_text(encoding="utf-8", errors="ignore")
    match = re.search(r'APP_VERSION\s*=\s*"([^"]+)"', text)
    return match.group(1) if match else "unknown"


def build_report() -> dict:
    issues: list[str] = []
    script = ROOT / "tools" / "create_release_zip.py"
    if not script.exists():
        issues.append("tools/create_release_zip.py missing")
    else:
        text = script.read_text(encoding="utf-8", errors="ignore")
        required = {
            "root folder constant": 'ROOT_FOLDER_NAME = "nexaoffice_worksuite"',
            "zip root write": 'zf.writestr(f"{ROOT_FOLDER_NAME}/", "")',
            "prefixed file writes": 'f"{ROOT_FOLDER_NAME}/{rel}"',
            "flat zip validation": "top_levels != [ROOT_FOLDER_NAME]",
        }
        for label, marker in required.items():
            if marker not in text:
                issues.append(f"create_release_zip.py missing marker: {label}")
    report = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "version": _version(),
        "status": "OK" if not issues else "FAILED",
        "required_root_folder": "nexaoffice_worksuite",
        "issues": issues,
    }
    return report


def main() -> int:
    report = build_report()
    REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
    REPORT_PATH.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print("Package structure:", report["status"])
    for issue in report["issues"][:20]:
        print("-", issue)
    return 0 if report["status"] == "OK" else 1


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