from __future__ import annotations

import shutil
import subprocess
from pathlib import Path


def openapi_to_ts_types(
    *,
    root_path: str,
    out_path: str,
    package_dir: str | None = None,
) -> None:
    """Generate TypeScript OpenAPI types through the target project's local npm tooling."""
    npm = shutil.which("npm")
    if npm is None:
        raise RuntimeError("未找到 npm；无法执行目标项目本地 openapi-typescript。")

    root = Path(root_path).resolve()
    out = Path(out_path).resolve()
    out.parent.mkdir(parents=True, exist_ok=True)
    cwd = Path(package_dir).resolve() if package_dir else Path.cwd()

    cmd = [
        npm,
        "exec",
        "--",
        "openapi-typescript",
        str(root),
        "-o",
        str(out),
    ]
    try:
        subprocess.run(cmd, cwd=str(cwd), check=True)
    except subprocess.CalledProcessError as exc:
        raise RuntimeError(
            "openapi-typescript 生成失败；请确认目标项目已安装 openapi-typescript。"
        ) from exc
