"""Registration failure classification — ported from yt-mcp's mcpRegistration.ts."""

from __future__ import annotations

from typing import Literal

MCP_REGISTER_TIMEOUT_MS = 5000

RegistrationFailureKind = Literal[
    "already_exists",
    "authentication",
    "timeout",
    "other",
]


class RegistrationFailure:
    """Result of a registration attempt failure."""

    def __init__(self, kind: RegistrationFailureKind, output: str = ""):
        self.kind = kind
        self.output = output

    def __repr__(self) -> str:
        return f"RegistrationFailure(kind={self.kind!r}, output={self.output[:50]!r}...)"


def _read_output(err: Exception) -> str:
    """Extract stderr + stdout from exception."""
    result = ""
    if hasattr(err, "stderr"):
        result += str(getattr(err, "stderr", "") or "")
    if hasattr(err, "stdout"):
        result += str(getattr(err, "stdout", "") or "")
    return result


def classify_registration_failure(err: Exception) -> RegistrationFailure:
    """Classify a registration failure based on error output.
    
    Args:
        err: The exception that was raised during registration
    
    Returns:
        RegistrationFailure with kind and output
    """
    output = _read_output(err)
    lower = output.lower()

    if "already exists" in lower:
        return RegistrationFailure("already_exists", output)

    if "waiting for authentication" in lower:
        return RegistrationFailure("authentication", output)

    if hasattr(err, "code") and getattr(err, "code") == "ETIMEDOUT":
        return RegistrationFailure("timeout", output)

    return RegistrationFailure("other", output)
