from __future__ import annotations

import hashlib
import json
import sys
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
EXE = ROOT / "dist" / "NexaOffice_WorkSuite" / "NexaOffice_WorkSuite.exe"
ICON = ROOT / "assets" / "nexaoffice.ico"


def sha256_small(path: Path, max_bytes: int = 512 * 1024 * 1024) -> str:
    if not path.exists() or not path.is_file():
        return ""
    try:
        if path.stat().st_size > max_bytes:
            return "skipped_large_file"
        h = hashlib.sha256()
        with path.open("rb") as f:
            for chunk in iter(lambda: f.read(1024 * 1024), b""):
                h.update(chunk)
        return h.hexdigest()
    except Exception as exc:
        return f"error:{exc}"


def read_version() -> str:
    try:
        text = (ROOT / "core" / "constants.py").read_text(encoding="utf-8", errors="ignore")
        marker = 'APP_VERSION = "'
        if marker in text:
            return text.split(marker, 1)[1].split('"', 1)[0]
    except Exception:
        pass
    return ""


def main() -> int:
    payload = {
        "ok": EXE.exists(),
        "created_at": datetime.now().isoformat(timespec="seconds"),
        "app_version": read_version(),
        "python": sys.version.split()[0],
        "exe": {
            "path": str(EXE),
            "exists": EXE.exists(),
            "size": EXE.stat().st_size if EXE.exists() else 0,
            "sha256": sha256_small(EXE),
        },
        "icon": {
            "path": str(ICON),
            "exists": ICON.exists(),
            "sha256": sha256_small(ICON),
        },
        "folders": {
            "dist": (ROOT / "dist").exists(),
            "build": (ROOT / "build").exists(),
            "build_backups": (ROOT / "build_backups").exists(),
            "build_logs": (ROOT / "build_logs").exists(),
        },
    }
    DATA.mkdir(parents=True, exist_ok=True)
    (DATA / "build_manifest_latest.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0 if payload["ok"] else 1


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