"""Hatch build hook that builds the React frontend before wheel packaging."""

from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path

from hatchling.builders.hooks.plugin.interface import BuildHookInterface


class ReactBuildHook(BuildHookInterface):
    PLUGIN_NAME = "custom"

    def initialize(self, version: str, build_data: dict) -> None:
        frontend_dir = Path(self.root) / "ui" / "frontend"
        if not (frontend_dir / "package.json").exists():
            return

        npm = shutil.which("npm")
        if npm is None and sys.platform == "win32":
            npm = shutil.which("npm.cmd")
        if npm is None:
            raise RuntimeError("npm not found on PATH — required to build the React frontend")

        subprocess.run([npm, "ci"], cwd=str(frontend_dir), check=True)
        subprocess.run([npm, "run", "build"], cwd=str(frontend_dir), check=True)
