from __future__ import annotations

import os
import subprocess
import sys
from importlib import resources
from pathlib import Path


def _binary_name() -> str:
    return "sglangmuxd.exe" if os.name == "nt" else "sglangmuxd"


def _resolve_binary_path() -> Path:
    override = os.environ.get("SGLANGMUX_BIN")
    if override:
        path = Path(override).expanduser()
        if path.exists():
            return path
        raise FileNotFoundError(f"SGLANGMUX_BIN does not exist: {path}")

    binary_name = _binary_name()
    binary = resources.files("sglangmux").joinpath("bin", binary_name)
    with resources.as_file(binary) as resolved:
        if resolved.exists():
            return resolved

    # Editable install fallback: run binary built in repo target dir.
    repo_root = Path(__file__).resolve().parents[1]
    candidates = [repo_root / "target" / "release" / binary_name]
    cargo_target = os.environ.get("CARGO_BUILD_TARGET")
    if cargo_target:
        candidates.insert(0, repo_root / "target" / cargo_target / "release" / binary_name)

    for candidate in candidates:
        if candidate.exists():
            return candidate

    raise FileNotFoundError(
        "Bundled sglangmux binary not found in package data or local target directory"
    )


def main() -> int:
    try:
        binary = _resolve_binary_path()
    except Exception as exc:
        print(f"sglangmux: failed to locate Rust binary: {exc}", file=sys.stderr)
        return 1

    cmd = [str(binary), *sys.argv[1:]]
    try:
        result = subprocess.run(cmd)
    except FileNotFoundError as exc:
        print(f"sglangmux: failed to execute binary: {exc}", file=sys.stderr)
        return 1
    return result.returncode


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