#!/usr/bin/env python3
"""
Build script for the Python library.

This script:
1. Cleans the pypi_publish directory
2. Builds the wheel and sdist
3. Outputs everything to pypi_publish/

Usage:
    python build_lib.py
"""

import shutil
import subprocess
import sys
from pathlib import Path


def clean_build_dir(build_dir: Path) -> None:
    """Remove all files from the build directory."""
    if build_dir.exists():
        print(f"Cleaning {build_dir}...")
        # Remove all files except .gitkeep
        for item in build_dir.iterdir():
            if item.name == ".gitkeep":
                continue
            if item.is_file():
                item.unlink()
            elif item.is_dir():
                shutil.rmtree(item)
        print(f"  Cleaned {build_dir}")


def build_package(build_dir: Path) -> bool:
    """Build the package using python-build."""
    print("\nBuilding package...")
    
    # Run build with output to pypi_publish
    cmd = [
        sys.executable, "-m", "build",
        "--outdir", str(build_dir),
        "--wheel",
        "--sdist",
        "."
    ]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )
        print(result.stdout)
        if result.stderr:
            print(result.stderr)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Build failed with code {e.returncode}")
        print(e.stdout)
        print(e.stderr)
        return False


def verify_build(build_dir: Path) -> None:
    """Verify the built artifacts."""
    print("\nVerifying build artifacts...")
    
    wheels = list(build_dir.glob("*.whl"))
    sdists = list(build_dir.glob("*.tar.gz"))
    
    if wheels:
        print(f"  ✓ Wheel: {wheels[0].name}")
    else:
        print("  ✗ No wheel found!")
    
    if sdists:
        print(f"  ✓ Source distribution: {sdists[0].name}")
    else:
        print("  ✗ No source distribution found!")


def main() -> int:
    """Main entry point."""
    project_root = Path(__file__).parent.resolve()
    build_dir = project_root / "pypi_publish"
    
    print("=" * 50)
    print("Building Python Library")
    print("=" * 50)
    
    # Ensure build directory exists
    build_dir.mkdir(exist_ok=True)
    
    # Clean previous builds
    clean_build_dir(build_dir)
    
    # Build package
    if not build_package(build_dir):
        return 1
    
    # Verify
    verify_build(build_dir)
    
    print("\n" + "=" * 50)
    print("Build complete!")
    print(f"Artifacts in: {build_dir}")
    print("=" * 50)
    
    return 0


if __name__ == "__main__":
    sys.exit(main())
