#!/usr/bin/env python3
"""Run a build command with reproducible BioMCP executable identity inputs."""

from __future__ import annotations

import os
from pathlib import Path
import subprocess
import sys


def git(root: Path, *args: str) -> str | None:
    result = subprocess.run(
        ["git", "-C", str(root), *args],
        check=False,
        capture_output=True,
        text=True,
    )
    value = result.stdout.strip()
    return value if result.returncode == 0 and value else None


def owned_git_root(root: Path) -> Path | None:
    value = git(root, "rev-parse", "--show-toplevel")
    if value is None:
        return None
    candidate = Path(value).resolve()
    return candidate if candidate == root.resolve() else None


def cargo_package_version(root: Path) -> str:
    # tomllib needs Python 3.11 and the gate hosts run older system Pythons;
    # cargo metadata reads the same manifest everywhere this wrapper runs.
    result = subprocess.run(
        ["cargo", "metadata", "--no-deps", "--format-version", "1"],
        check=False,
        capture_output=True,
        text=True,
        cwd=root,
    )
    if result.returncode != 0:
        raise SystemExit("with-build-identity: cargo metadata failed")
    import json

    manifest = str((root / "Cargo.toml").resolve())
    packages = json.loads(result.stdout)["packages"]
    for package in packages:
        if package["manifest_path"] == manifest:
            return package["version"]
    raise SystemExit("with-build-identity: cargo metadata omits this manifest")


def identity_environment(root: Path) -> dict[str, str]:
    environment = dict(os.environ)
    repository = owned_git_root(root)
    if repository is None:
        return environment

    package_version = environment.get("CARGO_PKG_VERSION")
    if package_version is None:
        package_version = cargo_package_version(root)
    base_sha = git(repository, "rev-parse", "--short=8", "HEAD") or "unknown"
    dirty = git(
        repository,
        "status",
        "--porcelain",
        "--untracked-files=no",
        "--",
        ".",
    ) is not None
    exact_tag = git(repository, "describe", "--tags", "--exact-match")
    revision = f"{base_sha}-dirty" if dirty and base_sha != "unknown" else base_sha
    if exact_tag == f"v{package_version}" and not dirty:
        version = package_version
    elif base_sha != "unknown":
        version = f"{package_version}+g{base_sha}{'.dirty' if dirty else ''}"
    else:
        version = package_version

    environment.setdefault("BIOMCP_BUILD_GIT_SHA", revision)
    environment.setdefault("BIOMCP_BUILD_VERSION", version)
    environment.setdefault(
        "BIOMCP_BUILD_DATE",
        git(repository, "log", "-1", "--format=%cI") or "unknown",
    )
    return environment


def main() -> None:
    if len(sys.argv) < 2:
        raise SystemExit("usage: tools/with-build-identity <command> [args ...]")
    root = Path.cwd()
    # Run the child to completion and pass its exit code through.
    # os.execvpe replaced this process, which on Windows exits 0 at
    # once while the child keeps running, so a build step passed
    # with no binary. sys.argv[1:] keeps argv[0] as
    # the program name; subprocess.run resolves it on PATH.
    completed = subprocess.run(
        sys.argv[1:],
        env=identity_environment(root),
        check=False,
    )
    raise SystemExit(completed.returncode)


if __name__ == "__main__":
    main()
