"""Shared helpers for packaged runtime repair entrypoints."""

from __future__ import annotations

import os
import subprocess
from dataclasses import dataclass


@dataclass(frozen=True)
class ProbeResult:
    """Structured result from a runtime health probe."""

    ok: bool
    output: str
    returncode: int


def repair_env() -> dict[str, str]:
    """Return a normalized env for runtime repair subprocesses."""
    env = os.environ.copy()
    env.setdefault("TORCH_DEVICE_BACKEND_AUTOLOAD", "0")
    return env


def print_banner(title: str) -> None:
    """Print a standard repair banner."""
    print("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
    print(title)
    print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")


def run_command(
    cmd: list[str],
    *,
    check: bool = True,
    capture_output: bool = False,
    timeout: int | None = None,
) -> subprocess.CompletedProcess[str]:
    """Run a subprocess under the normalized repair environment."""
    return subprocess.run(
        cmd,
        check=check,
        text=True,
        capture_output=capture_output,
        timeout=timeout,
        env=repair_env(),
    )


def run_python_probe(python_executable: str, script: str) -> ProbeResult:
    """Execute a Python probe script and capture its structured result."""
    result = run_command(
        [python_executable, "-c", script],
        check=False,
        capture_output=True,
    )
    output = (result.stdout or result.stderr or "").strip()
    return ProbeResult(ok=result.returncode == 0, output=output, returncode=result.returncode)


def refresh_profile(python_executable: str, *, timeout: int) -> bool:
    """Refresh cached hardware profile and print a normalized summary."""
    result = run_command(
        [python_executable, "-m", "sagellm", "profile", "--refresh"],
        check=False,
        capture_output=True,
        timeout=timeout,
    )
    if result.returncode == 0:
        print("  ✅ 硬件配置刷新完成")
        return True

    print("  ⚠️  硬件配置刷新失败（已跳过，继续返回修复结论）")
    summary = (result.stderr or result.stdout or "").strip().splitlines()[-20:]
    if summary:
        print("  ⚠️  失败摘要（最近 20 行）：")
        for line in summary:
            print(f"    {line}")
    return False


def pip_uninstall_best_effort(python_executable: str, packages: list[str]) -> None:
    """Best-effort pip uninstall used before runtime stack reinstall."""
    run_command(
        [python_executable, "-m", "pip", "uninstall", "-y", *packages],
        check=False,
        capture_output=True,
    )


def pip_install(
    python_executable: str, packages: list[str], *, extra_args: list[str] | None = None
) -> None:
    """Install packages with pip under the normalized repair environment."""
    cmd = [python_executable, "-m", "pip", "install", "--no-cache-dir", *packages]
    if extra_args:
        cmd.extend(extra_args)
    run_command(cmd)


def pip_install_probe(
    python_executable: str,
    packages: list[str],
    *,
    extra_args: list[str] | None = None,
) -> ProbeResult:
    """Attempt a pip install and capture the result instead of raising."""
    cmd = [python_executable, "-m", "pip", "install", "--no-cache-dir", *packages]
    if extra_args:
        cmd.extend(extra_args)
    result = run_command(cmd, check=False, capture_output=True)
    output = "\n".join(part for part in [result.stdout, result.stderr] if part).strip()
    return ProbeResult(ok=result.returncode == 0, output=output, returncode=result.returncode)


def run_sagellm_cli(
    python_executable: str, args: list[str], *, check: bool = False
) -> subprocess.CompletedProcess[str]:
    """Run sagellm CLI via the package module for packaged repair entrypoints."""
    return run_command([python_executable, "-m", "sagellm", *args], check=check)
