#!/usr/bin/env python3
"""
Build script for CutySoup C++ extension
"""

import subprocess
import sys
import os

def run_command(cmd, description):
    """Run a command and handle errors"""
    print(f"\n{description}...")
    print(f"Running: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("✓ Success")
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Failed with return code {e.returncode}")
        if e.stdout:
            print("STDOUT:", e.stdout)
        if e.stderr:
            print("STDERR:", e.stderr)
        return False

def main():
    """Main build function"""
    print("=== CutySoup Build Script ===")
    
    # Check if we're in the right directory
    if not os.path.exists("CMakeLists.txt"):
        print("Error: CMakeLists.txt not found. Run this script from the project root.")
        sys.exit(1)
    
    # Install build dependencies
    print("\nInstalling build dependencies...")
    deps = ["scikit-build-core", "pybind11", "cmake", "ninja", "pytest"]
    for dep in deps:
        if not run_command([sys.executable, "-m", "pip", "install", dep], 
                          f"Installing {dep}"):
            print(f"Warning: Failed to install {dep}")
    
    # Build the extension
    if not run_command([sys.executable, "-m", "pip", "install", "-e", "."], 
                      "Building CutySoup extension"):
        print("Build failed!")
        sys.exit(1)
    
    print("\n✓ Build completed successfully!")
    print("\nYou can now run:")
    print("  python demo.py          # Run the demo")
    print("  python -m pytest tests/ # Run tests")

if __name__ == "__main__":
    main()