#!/usr/bin/env python3
"""
Daneshyar — Frontend Build (run locally before deploy)
Run: python scripts/build.py
"""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def find_cmd(name: str) -> str | None:
    if os.name == "nt":
        for suffix in (".cmd", ".bat", ".exe"):
            found = shutil.which(name + suffix)
            if found:
                return found
    return shutil.which(name)


def run(command: list[str], extra_env: dict | None = None) -> None:
    env = {**os.environ, **(extra_env or {})}
    print(f"\n> {' '.join(command)}")
    result = subprocess.run(command, cwd=ROOT, env=env)
    if result.returncode != 0:
        print(f"\nFAILED (exit {result.returncode}): {' '.join(command)}")
        sys.exit(result.returncode)


def main() -> None:
    print("=" * 50)
    print("  Daneshyar — Production Build")
    print("=" * 50)

    # ── Check prerequisites ────────────────────────────────────────────────────
    if not (ROOT / "package.json").exists():
        print("ERROR: package.json not found. Run from project root.")
        sys.exit(1)

    npm = find_cmd("npm")
    if not npm:
        print("ERROR: npm not found. Install Node.js: https://nodejs.org/")
        sys.exit(1)

    print(f"\n  npm:  {npm}")
    print(f"  root: {ROOT}")

    # ── npm install (include devDependencies — tsc/vite need them) ─────────────
    print("\n[1/2] npm install (all deps including dev)...")
    lock = (ROOT / "package-lock.json").exists()
    # Do NOT set NODE_ENV=production here — it skips devDependencies (tsc, @types/*)
    run([npm, "ci" if lock else "install"])

    # Verify tsc installed
    tsc = ROOT / "node_modules" / ".bin" / ("tsc.cmd" if os.name == "nt" else "tsc")
    if not tsc.exists():
        print("ERROR: tsc not found in node_modules/.bin after npm install.")
        print("  Check that 'typescript' is in devDependencies in package.json.")
        sys.exit(1)

    # ── npm run build (production mode for Vite output) ───────────────────────
    print("\n[2/2] Build assets (tsc type-check + vite build)...")
    run([npm, "run", "build"], extra_env={"NODE_ENV": "production"})

    # ── Verify output ──────────────────────────────────────────────────────────
    manifest = ROOT / "public" / "build" / "manifest.json"
    if not manifest.exists():
        print("\nERROR: public/build/manifest.json missing — Vite build failed.")
        sys.exit(1)

    build_dir = ROOT / "public" / "build"
    files = list(build_dir.rglob("*"))
    asset_count = sum(1 for f in files if f.is_file())
    size_kb = sum(f.stat().st_size for f in files if f.is_file()) // 1024

    print(f"\n{'=' * 50}")
    print(f"  BUILD COMPLETE")
    print(f"{'=' * 50}")
    print(f"  Output: public/build/  ({asset_count} files, {size_kb} KB)")
    print(f"\n  Next: python scripts/deploy.py")


if __name__ == "__main__":
    main()
