#!/usr/bin/env python3
"""
Build script for SWE Agent PyPI package
"""

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

def build_package():
    """Build the SWE Agent package"""
    print("🚀 Building SWE Agent PyPI package...")
    
    # Clean previous builds
    print("🧹 Cleaning previous builds...")
    dirs_to_clean = ["build", "dist", "swe_agent.egg-info"]
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
            print(f"   Removed {dir_name}")
    
    # Build the package
    print("📦 Building package...")
    try:
        subprocess.run([sys.executable, "-m", "build"], check=True)
        print("✅ Package built successfully!")
        
        # List the built files
        if os.path.exists("dist"):
            print("\n📋 Built files:")
            for file in os.listdir("dist"):
                print(f"   - {file}")
        
        print("\n🎉 Package ready for upload!")
        print("To upload to PyPI:")
        print("   pip install twine")
        print("   twine upload dist/*")
        
    except subprocess.CalledProcessError as e:
        print(f"❌ Build failed: {e}")
        return False
    
    return True

def install_build_dependencies():
    """Install build dependencies"""
    print("📥 Installing build dependencies...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "build", "twine"], check=True)
        print("✅ Dependencies installed!")
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install dependencies: {e}")
        return False
    return True

def test_package():
    """Test the package installation"""
    print("🧪 Testing package installation...")
    try:
        # Install in development mode
        subprocess.run([sys.executable, "-m", "pip", "install", "-e", "."], check=True)
        print("✅ Package installed in development mode!")
        
        # Test the CLI
        result = subprocess.run(["swe-agent", "--help"], capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ CLI command works!")
            return True
        else:
            print(f"❌ CLI test failed: {result.stderr}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"❌ Package installation failed: {e}")
        return False

if __name__ == "__main__":
    print("SWE Agent Package Builder")
    print("=" * 30)
    
    if not install_build_dependencies():
        sys.exit(1)
    
    if not test_package():
        sys.exit(1)
    
    if not build_package():
        sys.exit(1)
    
    print("\n🎯 Next steps:")
    print("1. Test the package: pip install dist/swe_agent-1.0.0-py3-none-any.whl")
    print("2. Upload to PyPI: twine upload dist/*")
    print("3. Install from PyPI: pip install swe-agent")