"""Collect environment diagnostics for feedback and doctor commands."""

from __future__ import annotations

import platform
import shutil
from pathlib import Path


def get_diagnostics_string(*, tier: str = "community", cloud: str | None = None) -> str:
    """Build diagnostics string — no PII, no secrets."""
    from complyform import __version__

    parts = [f"complyform={__version__}"]
    parts.append(f"python={platform.python_version()}")

    checkov_path = shutil.which("checkov")
    if checkov_path:
        parts.append("checkov=installed")
    else:
        parts.append("checkov=not-found")

    iac_binary = _detect_iac_binary()
    parts.append(f"iac={iac_binary}")

    parts.append(f"os={platform.system()}/{platform.machine()}")
    parts.append(f"tier={tier}")
    if cloud:
        parts.append(f"cloud={cloud}")

    cache_info = _cache_info()
    parts.append(f"cache={cache_info}")

    return " ".join(parts)


def _detect_iac_binary() -> str:
    """Detect tofu or terraform on PATH."""
    for binary in ("tofu", "terraform"):
        if shutil.which(binary):
            return binary
    return "none"


def _cache_info() -> str:
    """Count cache entries and total size."""
    cache_dir = Path.home() / ".complyform" / "cache"
    if not cache_dir.exists():
        return "0/0B"
    count = 0
    total_size = 0
    for entry in cache_dir.iterdir():
        if entry.is_dir():
            count += 1
            for f in entry.iterdir():
                if f.is_file():
                    total_size += f.stat().st_size
    if total_size < 1024:
        size_str = f"{total_size}B"
    elif total_size < 1024 * 1024:
        size_str = f"{total_size // 1024}KB"
    else:
        size_str = f"{total_size // (1024 * 1024)}MB"
    return f"{count}/{size_str}"
