"""AI 服务错误码定义（前缀 AI_*）.

依据 02-architecture-design.md §6.2 错误码清单.
"""

from enum import StrEnum


class ErrorCode(StrEnum):
    """错误码枚举."""

    AI_UNAUTHORIZED = "AI_UNAUTHORIZED"
    AI_FORBIDDEN = "AI_FORBIDDEN"
    AI_RATE_LIMITED = "AI_RATE_LIMITED"
    AI_QUOTA_EXCEEDED = "AI_QUOTA_EXCEEDED"
    AI_LLM_UNAVAILABLE = "AI_LLM_UNAVAILABLE"
    AI_LLM_TIMEOUT = "AI_LLM_TIMEOUT"
    AI_LLM_ALL_PROVIDERS_FAILED = "AI_LLM_ALL_PROVIDERS_FAILED"
    AI_INVALID_MODEL = "AI_INVALID_MODEL"
    AI_INVALID_DIFFICULTY = "AI_INVALID_DIFFICULTY"
    AI_INVALID_QUESTION_TYPE = "AI_INVALID_QUESTION_TYPE"
    AI_DOWNSTREAM_UNAVAILABLE = "AI_DOWNSTREAM_UNAVAILABLE"
    AI_PROMPT_RENDER_FAILED = "AI_PROMPT_RENDER_FAILED"
    AI_PROMPT_TEMPLATE_NOT_FOUND = "AI_PROMPT_TEMPLATE_NOT_FOUND"
    AI_WORKFLOW_NOT_FOUND = "AI_WORKFLOW_NOT_FOUND"
    AI_WORKFLOW_EXPIRED = "AI_WORKFLOW_EXPIRED"
    AI_WORKFLOW_STATE_INVALID = "AI_WORKFLOW_STATE_INVALID"
    AI_EVALUATION_FAILED = "AI_EVALUATION_FAILED"
    AI_PII_DETECTED = "AI_PII_DETECTED"
    AI_PROMPT_INJECTION_DETECTED = "AI_PROMPT_INJECTION_DETECTED"
    AI_CONTENT_MODERATION_REJECTED = "AI_CONTENT_MODERATION_REJECTED"
    AI_INTERNAL_ERROR = "AI_INTERNAL_ERROR"


class ErrorCodes:
    """错误码 → HTTP 状态码 + gRPC status 映射."""

    HTTP_STATUS: dict[ErrorCode, int] = {
        ErrorCode.AI_UNAUTHORIZED: 401,
        ErrorCode.AI_FORBIDDEN: 403,
        ErrorCode.AI_RATE_LIMITED: 429,
        ErrorCode.AI_QUOTA_EXCEEDED: 429,
        ErrorCode.AI_LLM_UNAVAILABLE: 200,  # 降级模式仍返回 200
        ErrorCode.AI_LLM_TIMEOUT: 504,
        ErrorCode.AI_LLM_ALL_PROVIDERS_FAILED: 503,
        ErrorCode.AI_INVALID_MODEL: 400,
        ErrorCode.AI_INVALID_DIFFICULTY: 400,
        ErrorCode.AI_INVALID_QUESTION_TYPE: 400,
        ErrorCode.AI_DOWNSTREAM_UNAVAILABLE: 502,
        ErrorCode.AI_PROMPT_RENDER_FAILED: 500,
        ErrorCode.AI_PROMPT_TEMPLATE_NOT_FOUND: 404,
        ErrorCode.AI_WORKFLOW_NOT_FOUND: 404,
        ErrorCode.AI_WORKFLOW_EXPIRED: 410,
        ErrorCode.AI_WORKFLOW_STATE_INVALID: 409,
        ErrorCode.AI_EVALUATION_FAILED: 503,
        ErrorCode.AI_PII_DETECTED: 400,
        ErrorCode.AI_PROMPT_INJECTION_DETECTED: 400,
        ErrorCode.AI_CONTENT_MODERATION_REJECTED: 503,
        ErrorCode.AI_INTERNAL_ERROR: 500,
    }

    @classmethod
    def http_status(cls, code: ErrorCode) -> int:
        return cls.HTTP_STATUS.get(code, 500)
