"""ANSI color helpers for terminal output.

Respects NO_COLOR env var (https://no-color.org/) and pipe detection.
"""

from __future__ import annotations

import os
import sys


def _color_enabled() -> bool:
    """Check if color output should be enabled."""
    if os.environ.get("NO_COLOR"):
        return False
    if os.environ.get("MCPAUDIT_NO_COLOR"):
        return False
    return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()


_ENABLED = _color_enabled()


# ANSI codes
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"

RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
GRAY = "\033[90m"

BG_RED = "\033[41m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
BG_MAGENTA = "\033[45m"


def c(text: str, *codes: str) -> str:
    """Wrap text with ANSI codes if color is enabled."""
    if not _ENABLED:
        return text
    prefix = "".join(codes)
    return f"{prefix}{text}{RESET}"


def disable_color() -> None:
    """Disable color output globally."""
    global _ENABLED
    _ENABLED = False


def severity_color(severity_value: str) -> str:
    """Get the ANSI color code for a severity level."""
    return {
        "CRITICAL": RED,
        "HIGH": YELLOW,
        "MEDIUM": MAGENTA,
        "LOW": CYAN,
        "INFO": GRAY,
    }.get(severity_value, "")


def grade_color(grade: str) -> str:
    """Get the ANSI color code for a grade."""
    if grade.startswith("A"):
        return GREEN
    if grade == "B":
        return CYAN
    if grade == "C":
        return YELLOW
    if grade == "D":
        return MAGENTA
    return RED  # F


def trust_label_color(label: str) -> str:
    """Get the ANSI color code for a trust score label."""
    label_upper = label.upper()
    if label_upper in ("EXCELLENT", "GOOD"):
        return GREEN
    if label_upper == "MODERATE":
        return YELLOW
    if label_upper == "LOW":
        return MAGENTA
    return RED  # CRITICAL
