#!/usr/bin/env python3
"""
Build script to compile the taco binary and make it available in the Python package.
"""

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

def run_command(cmd, check=True):
    """Run a command and return the result."""
    print(f"Running: {' '.join(cmd)}")
    return subprocess.run(cmd, check=check)

def find_cargo():
    """Find the cargo executable."""
    cargo_cmd = "cargo"
    if platform.system() == "Windows":
        cargo_cmd += ".exe"
    
    if shutil.which(cargo_cmd):
        return cargo_cmd
    
    # Try common installation paths
    home = Path.home()
    cargo_paths = [
        home / ".cargo" / "bin" / cargo_cmd,
        Path("/usr/local/bin") / cargo_cmd,
    ]
    
    for path in cargo_paths:
        if path.exists():
            return str(path)
    
    return None

def build_binary():
    """Build the taco binary."""
    cargo = find_cargo()
    if not cargo:
        print("Warning: Cargo not found. Skipping binary build.")
        return False
    
    print("Building taco binary...")
    try:
        run_command([cargo, "build", "--release", "--bin", "taco"])
        return True
    except subprocess.CalledProcessError as e:
        print(f"Warning: Failed to build binary: {e}")
        return False

def main():
    """Main build function."""
    print("TACO Format Build Script")
    print("========================")
    
    # Change to the project root
    script_dir = Path(__file__).parent
    os.chdir(script_dir)
    
    # Build the binary
    if build_binary():
        print("Binary built successfully!")
        
        # Check if binary exists
        binary_name = "taco"
        if platform.system() == "Windows":
            binary_name += ".exe"
        
        binary_path = Path("target") / "release" / binary_name
        if binary_path.exists():
            print(f"Binary available at: {binary_path}")
        else:
            print("Warning: Binary not found after build")
    else:
        print("Binary build failed or skipped")

if __name__ == "__main__":
    main()
