"""Main file to build the frontend."""

import os
import subprocess
import shutil
import sys


def get_npm_command():
    """Get the appropriate npm command for the current OS."""
    if sys.platform == "win32":
        return "npm.cmd"
    return "npm"


def build_frontend():
    """Build the frontend."""
    frontend_dir = "cdrm-frontend"
    npm_cmd = get_npm_command()

    # Check and install dependencies if node_modules doesn't exist
    if not os.path.exists(f"{frontend_dir}/node_modules"):
        print("📦 Installing dependencies...")
        subprocess.run([npm_cmd, "install"], cwd=frontend_dir, check=True)

    # Always build the frontend to ensure it's up to date
    print("🔨 Building frontend...")
    subprocess.run([npm_cmd, "run", "build"], cwd=frontend_dir, check=True)

    # Move dist to frontend-dist
    if os.path.exists("frontend-dist"):
        shutil.rmtree("frontend-dist")
    shutil.copytree(f"{frontend_dir}/dist", "frontend-dist")

    print("✅ Build complete. Run the application with 'python main.py'")


if __name__ == "__main__":
    build_frontend()
