#!/usr/bin/env python3
import os
import subprocess
import shutil
import sys
from pathlib import Path

def run_command(command, cwd=None):
    """Run a shell command and print output"""
    print(f"Running: {command}")
    result = subprocess.run(command, shell=True, check=False, 
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           text=True, cwd=cwd)
    
    print(result.stdout)
    if result.stderr:
        print(f"Error: {result.stderr}")
    
    if result.returncode != 0:
        print(f"Command failed with return code {result.returncode}")
        return False
    
    return True

def main():
    # Get the current directory (assuming this is the jsonl-parser directory)
    base_dir = os.getcwd()
    
    # Determine if we need to create a build directory
    parser_dir = os.path.join(base_dir, "jsonl-parser")
    build_dir = os.path.join(parser_dir, "build")
    
    # Create build directory if it doesn't exist
    os.makedirs(build_dir, exist_ok=True)
    
    # Check if there's a CMakeLists.txt in the parser directory
    if not os.path.exists(os.path.join(parser_dir, "CMakeLists.txt")):
        print("Error: CMakeLists.txt not found in the parser directory.")
        print(f"Expected at: {os.path.join(parser_dir, 'CMakeLists.txt')}")
        return False
    
    # Configure with CMake
    if not run_command("cmake -DCMAKE_BUILD_TYPE=Release ..", cwd=build_dir):
        return False
    
    # Build with multiple cores
    cpu_count = os.cpu_count() or 2
    if not run_command(f"make -j{cpu_count}", cwd=build_dir):
        return False
    
    # Check if the build was successful by looking for executable files
    executables = list(Path(build_dir).glob("**/*"))
    executables = [exe for exe in executables if os.access(exe, os.X_OK) and exe.is_file()]
    
    if executables:
        print("\nBuild successful! Executables found:")
        for exe in executables:
            print(f" - {exe}")
    else:
        print("\nBuild completed, but no executables were found.")
        print("Check the CMake configuration to ensure it's generating executables.")
    
    # Copy only the 'parser' executable to the base directory for easier access
    for exe in executables:
        if exe.name == "parser":
            target_path = os.path.join(base_dir, exe.name)
            print(f"Copying {exe} to {target_path}")
            shutil.copy2(exe, target_path)
            break
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)