from __future__ import annotations

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

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
DIST_EXE = ROOT / "dist" / "NexaOffice_WorkSuite" / "NexaOffice_WorkSuite.exe"
SPEC = ROOT / "nexaoffice_worksuite.spec"
CONSTANTS = ROOT / "core" / "constants.py"
MANIFEST = ROOT / "nexaoffice.exe.manifest"
VERSION_INFO = ROOT / "version_info.txt"
SECURITY_PREFLIGHT = DATA / "security_preflight_latest.json"
CODE_SIGNING = DATA / "code_signing_latest.json"
DEFENDER_SCAN = DATA / "windows_defender_scan_latest.json"


def sha256(path: Path) -> str | None:
    if not path.exists() or not path.is_file():
        return None
    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()


def current_version() -> str:
    try:
        text = CONSTANTS.read_text(encoding="utf-8")
        match = re.search(r'APP_VERSION\s*=\s*"(v\d{4}\.\d{2}\.\d{2}\.\d{2,3})"', text)
        return match.group(1) if match else "unknown"
    except Exception:
        return "unknown"


def spec_flags() -> dict:
    text = SPEC.read_text(encoding="utf-8", errors="ignore") if SPEC.exists() else ""
    return {
        "pyinstaller_mode": "onedir / COLLECT",
        "onefile": False,
        "upx_disabled": "upx=False" in text,
        "python_archive_disabled_noarchive": "noarchive=True" in text,
        "admin_privilege_requested": "requireAdministrator" in (MANIFEST.read_text(encoding="utf-8", errors="ignore") if MANIFEST.exists() else ""),
        "console_window": "console=True" in text,
        "version_info_present": VERSION_INFO.exists(),
        "manifest_present": MANIFEST.exists(),
        "icon_present": (ROOT / "assets" / "nexaoffice.ico").exists(),
    }


def main() -> int:
    payload = {
        "app": "NexaOffice WorkSuite",
        "version": current_version(),
        "created_at": datetime.now().isoformat(timespec="seconds"),
        "purpose": "Build transparency report for antivirus false-positive review and internal release checks.",
        "important_note": "This report is not a security certificate. Public distribution should use code signing and vendor false-positive submission if a generic detection appears.",
        "build_flags": spec_flags(),
        "files": {
            "exe": {
                "path": str(DIST_EXE),
                "exists": DIST_EXE.exists(),
                "size_bytes": DIST_EXE.stat().st_size if DIST_EXE.exists() else 0,
                "sha256": sha256(DIST_EXE),
            },
            "spec_sha256": sha256(SPEC),
            "manifest_sha256": sha256(MANIFEST),
            "version_info_sha256": sha256(VERSION_INFO),
            "main_py_sha256": sha256(ROOT / "main.py"),
            "app_py_sha256": sha256(ROOT / "app.py"),
        },
        "source_policy": {
            "runtime_data_location": "AppData/NexaOffice/data by default; portable.flag enables local data folder.",
            "native_notifications": "Optional; the main EXE no longer requires plyer for the build.",
            "network": "Offline-first by default. Only the manually configured sync/API origin is contacted after the user enables online mode; no hidden updater is bundled.",
            "http_policy": "HTTPS is preferred. Plain HTTP is blocked except localhost/127.0.0.1 development tests.",
            "network_audit": "Manual network tests write data/network_audit.json without tokens, request bodies, query strings, or full paths.",
        },
        "security_reports": {
            "security_preflight": {
                "path": str(SECURITY_PREFLIGHT),
                "exists": SECURITY_PREFLIGHT.exists(),
                "sha256": sha256(SECURITY_PREFLIGHT),
            },
            "code_signing": {
                "path": str(CODE_SIGNING),
                "exists": CODE_SIGNING.exists(),
                "sha256": sha256(CODE_SIGNING),
            },
            "windows_defender_scan": {
                "path": str(DEFENDER_SCAN),
                "exists": DEFENDER_SCAN.exists(),
                "sha256": sha256(DEFENDER_SCAN),
            },
        },
        "windows_distribution_note": {
            "defender_and_smartscreen": "Defender can scan the file, but SmartScreen reputation improves mainly through valid code signing and download/install reputation over time.",
            "recommended_public_release": "Use an OV/EV code-signing certificate and keep stable product/version metadata. Submit false positives to Microsoft/Avast/other vendors with the EXE hash and package_trust_report.",
        },
    }
    DATA.mkdir(parents=True, exist_ok=True)
    out = DATA / "package_trust_report_latest.json"
    out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    # The source package may not have a built EXE yet, so this is advisory and should not fail the build.
    return 0


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