#!/usr/bin/env python3
"""
MOXIE Build Script
Builds a standalone executable using Nuitka.
"""
import subprocess
import sys
import os
from pathlib import Path

# Project root
PROJECT_ROOT = Path(__file__).parent

# Build configuration
BUILD_CONFIG = {
    "main_module": "main.py",
    "output_filename": "moxie",
    "packages": [
        "fastapi",
        "uvicorn",
        "pydantic",
        "pydantic_settings",
        "ollama",
        "httpx",
        "aiohttp",
        "duckduckgo_search",
        "wikipedia",
        "jinja2",
        "pypdf",
        "docx",
        "bs4",
        "loguru",
        "websockets",
        "numpy",
    ],
    "include_data_dirs": [
        ("admin/templates", "admin/templates"),
        ("admin/static", "admin/static"),
    ],
}


def build():
    """Build the executable using Nuitka."""
    print("=" * 60)
    print("MOXIE Build Script")
    print("=" * 60)
    
    # Change to project directory
    os.chdir(PROJECT_ROOT)
    
    # Build command
    cmd = [
        sys.executable,
        "-m",
        "nuitka",
        "--standalone",
        "--onefile",
        "--onefile-no-compression",
        "--assume-yes-for-downloads",
        f"--output-filename={BUILD_CONFIG['output_filename']}",
        "--enable-plugin=multiprocessing",
    ]
    
    # Add packages
    for pkg in BUILD_CONFIG["packages"]:
        cmd.append(f"--include-package={pkg}")
    
    # Add data directories
    for src, dst in BUILD_CONFIG["include_data_dirs"]:
        src_path = PROJECT_ROOT / src
        if src_path.exists():
            cmd.append(f"--include-data-dir={src}={dst}")
    
    # Add main module
    cmd.append(BUILD_CONFIG["main_module"])
    
    print("\nRunning Nuitka build...")
    print(" ".join(cmd[:10]), "...")
    print()
    
    # Run build
    result = subprocess.run(cmd, cwd=PROJECT_ROOT)
    
    if result.returncode == 0:
        print("\n" + "=" * 60)
        print("BUILD SUCCESSFUL!")
        print(f"Executable: {BUILD_CONFIG['output_filename']}")
        print("=" * 60)
    else:
        print("\n" + "=" * 60)
        print("BUILD FAILED!")
        print("=" * 60)
        sys.exit(1)


if __name__ == "__main__":
    build()
