from __future__ import annotations

import subprocess
import sys
import time
from typing import Any

from . import error_logging


def run_cli_hidden(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
    """Run CLI helpers from the GUI app without flashing a Windows console."""
    diagnostic_operation = str(kwargs.pop("diagnostic_operation", "") or "").strip()
    raw_diagnostic_context = kwargs.pop("diagnostic_context", None)
    diagnostic_context = raw_diagnostic_context if isinstance(raw_diagnostic_context, dict) else {}
    started = time.perf_counter()
    if sys.platform.startswith("win"):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = 0
        kwargs.setdefault("startupinfo", startupinfo)
        kwargs["creationflags"] = int(kwargs.get("creationflags", 0)) | getattr(subprocess, "CREATE_NO_WINDOW", 0)
    try:
        result = subprocess.run(command, **kwargs)
    except Exception as exc:
        if diagnostic_operation:
            error_logging.log_exception(
                exc,
                component="subprocess",
                operation=diagnostic_operation,
                context={"executable": command[0] if command else "", **diagnostic_context},
            )
        raise
    if diagnostic_operation and result.returncode != 0:
        error_logging.log_error(
            "subprocess",
            "External process failed",
            context={
                "operation": diagnostic_operation,
                "executable": command[0] if command else "",
                "exitCode": result.returncode,
                "durationMs": int((time.perf_counter() - started) * 1000),
                "stdout": str(result.stdout or "")[:4000],
                "stderr": str(result.stderr or "")[:4000],
                **diagnostic_context,
            },
        )
    return result
