#!/usr/bin/env python3
"""Test wheel building locally using cibuildwheel."""

import subprocess
import sys
import os
import platform

def test_local_wheel_build():
    """Test building wheels for the current platform."""
    
    # Determine current platform
    system = platform.system()
    machine = platform.machine()
    
    print(f"Testing wheel build on {system} {machine}")
    
    # Set up environment
    env = os.environ.copy()
    
    if system == "Darwin":  # macOS
        if machine == "arm64":
            env["CIBW_ARCHS"] = "arm64"
        else:
            env["CIBW_ARCHS"] = "x86_64"
        env["CIBW_BUILD"] = "cp311-*"  # Just test one Python version
    elif system == "Linux":
        env["CIBW_ARCHS"] = "x86_64"
        env["CIBW_BUILD"] = "cp311-*"
    else:
        print(f"Unsupported platform: {system}")
        return False
    
    # Common settings
    env["CIBW_SKIP"] = "*-musllinux_* *-manylinux_i686"
    env["CIBW_BEFORE_BUILD"] = "pip install numpy pybind11 && python scripts/download_eigen.py ."
    
    # Download Eigen first
    print("Downloading Eigen...")
    subprocess.run([sys.executable, "scripts/download_eigen.py", "."], check=True)
    
    # Run cibuildwheel
    print("\nBuilding wheels with cibuildwheel...")
    try:
        subprocess.run(
            [sys.executable, "-m", "cibuildwheel", "--platform", "auto"],
            env=env,
            check=True
        )
        print("\n✓ Wheel build successful!")
        
        # List built wheels
        if os.path.exists("wheelhouse"):
            wheels = [f for f in os.listdir("wheelhouse") if f.endswith(".whl")]
            print(f"\nBuilt {len(wheels)} wheel(s):")
            for wheel in wheels:
                print(f"  - {wheel}")
        
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"\n✗ Wheel build failed: {e}")
        return False
    except FileNotFoundError:
        print("\n✗ cibuildwheel not found. Install with: pip install cibuildwheel")
        return False

if __name__ == "__main__":
    # Check if cibuildwheel is installed
    try:
        import cibuildwheel
        print(f"Using cibuildwheel version {cibuildwheel.__version__}")
    except ImportError:
        print("Installing cibuildwheel...")
        subprocess.run([sys.executable, "-m", "pip", "install", "cibuildwheel"], check=True)
    
    success = test_local_wheel_build()
    sys.exit(0 if success else 1)