#!/usr/bin/env python3
"""Resolve bundled lark-cli binary path by platform."""

from __future__ import annotations

import platform
from pathlib import Path


def _norm_os() -> str:
    system = platform.system().lower()
    if system.startswith("darwin"):
        return "darwin"
    if system.startswith("linux"):
        return "linux"
    if system.startswith("windows"):
        return "windows"
    return system


def _norm_arch() -> str:
    machine = platform.machine().lower()
    mapping = {
        "x86_64": "amd64",
        "amd64": "amd64",
        "aarch64": "arm64",
        "arm64": "arm64",
    }
    return mapping.get(machine, machine)


def resolve_bundled_cli(base_dir: Path) -> Path:
    os_name = _norm_os()
    arch = _norm_arch()
    ext = ".exe" if os_name == "windows" else ""

    # New multi-platform layout.
    candidate = base_dir / "bin" / f"{os_name}-{arch}" / f"lark-cli-openclaw{ext}"
    if candidate.exists():
        return candidate

    # Backward compatibility: old single-binary layout.
    old = base_dir / "bin" / f"lark-cli-openclaw{ext}"
    if old.exists():
        return old

    supported = [
        "darwin-amd64",
        "darwin-arm64",
        "linux-amd64",
        "linux-arm64",
        "windows-amd64",
        "windows-arm64",
    ]
    raise FileNotFoundError(
        f"missing bundled lark-cli-openclaw for {os_name}-{arch}; "
        f"expected {candidate}. supported targets: {', '.join(supported)}"
    )
