"""Build the Go `astra` binary during `pip install` and ship it inside the Python package."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from setuptools import setup
from setuptools.command.build_py import build_py

ROOT = Path(__file__).resolve().parent
PKG_DIR = ROOT / "wati_astra_cli"


class BuildPy(build_py):
    def run(self) -> None:
        self._build_astra_binary()
        super().run()

    def _build_astra_binary(self) -> None:
        exe_name = "_astra_bin.exe" if sys.platform == "win32" else "_astra_bin"
        out = PKG_DIR / exe_name
        try:
            subprocess.run(
                ["go", "version"],
                cwd=ROOT,
                check=True,
                capture_output=True,
            )
        except FileNotFoundError as e:
            raise RuntimeError(
                "Building wati-astra-cli from source requires Go on PATH. "
                "Install from https://go.dev/dl/ or use `go install .../cmd/astra@latest`."
            ) from e
        except subprocess.CalledProcessError as e:
            raise RuntimeError("Go toolchain found but `go version` failed.") from e

        proc = subprocess.run(
            ["go", "build", "-ldflags", "-s -w", "-o", str(out), "./cmd/astra"],
            cwd=ROOT,
        )
        if proc.returncode != 0:
            raise RuntimeError("go build failed while building astra binary for pip package.")


if __name__ == "__main__":
    _exe = "_astra_bin.exe" if sys.platform == "win32" else "_astra_bin"
    setup(
        cmdclass={"build_py": BuildPy},
        package_data={"wati_astra_cli": [_exe]},
    )
