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


####
##  Main function
####
def main() -> int:
    """Build the CLI binary and copy it to the falcorn-python/falcorn/bin directory."""
    if os.environ.get("FALCORN_SKIP_CLI", "").lower() in {"1", "true", "yes", "on"}:
        print("Skipping CLI build (FALCORN_SKIP_CLI=1).")
        return 0

    root = Path(__file__).resolve().parents[2]
    bin_dir = root / "falcorn-python" / "falcorn" / "bin"
    bin_dir.mkdir(parents=True, exist_ok=True)

    cmd = ["cargo", "build", "-p", "falcorn-cli", "--release"]

    # Add pyo3/abi3-py310 feature
    # cmd.extend(["--features", "pyo3/abi3-py310"])

    print("Running:", " ".join(cmd))
    env = os.environ.copy()
    cli_python = env.get("FALCORN_CLI_PYTHON")
    if cli_python:
        env["PYO3_PYTHON"] = cli_python
        print("Using PYO3_PYTHON for CLI build:", cli_python)
    subprocess.check_call(cmd, cwd=root, env=env)

    exe = "falcorn.exe" if sys.platform.startswith("win") else "falcorn"
    src = root / "target" / "release" / exe
    if not src.exists():
        raise FileNotFoundError(f"Expected CLI binary at {src}")

    dst = bin_dir / exe
    shutil.copy2(src, dst)
    print("Copied CLI to", dst)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
