"""
Error enrichment for user-friendly error messages.

Converts generic exceptions into structured errors with actionable suggestions.
"""

import traceback
from typing import Any


def enrich_error(stage: str, exception: Exception) -> dict[str, Any]:
    """
    Convert generic exception to user-actionable structured error.

    Args:
        stage: Stage where error occurred (e.g., "usage", "metadata")
        exception: The caught exception

    Returns:
        Structured error dict with keys:
            - stage: str
            - error_type: str (exception class name)
            - message: str (user-friendly message)
            - field: str | None (config field that failed)
            - suggestion: str | None (how to fix)
            - traceback: str (full traceback for debugging)
    """
    error_msg = str(exception).lower()
    error_type = type(exception).__name__

    # Pattern matching for common errors
    field = None
    suggestion = None

    # Dataset not found
    if "dataset" in error_msg and "not found" in error_msg:
        error_type = "ConfigError"
        field = "dataset_name"
        suggestion = "Run 'czbg list-datasets' to see available datasets. Verify the dataset_name in your config matches an existing dataset."

    # Reference data missing
    elif "reference" in error_msg and ("missing" in error_msg or "not found" in error_msg):
        error_type = "DataError"
        field = None
        suggestion = "Reference data failed to download from S3. Check AWS credentials and S3 bucket access permissions."

    # Insufficient resources (K8s)
    elif "insufficient" in error_msg and "resources" in error_msg:
        error_type = "ValidationError"
        field = None
        suggestion = "K8s stage requires more compute resources. Increase resource_count in generate config (need 53+ resources) or reduce clusters/workloads in k8s config."

    # Invalid provider
    elif "unsupported" in error_msg and "provider" in error_msg:
        error_type = "ConfigError"
        field = "provider"
        suggestion = "Valid providers: AWS, Azure, GCP, Oracle Cloud. Note: provider names are case-sensitive."

    # S3 access denied
    elif "access denied" in error_msg or "forbidden" in error_msg:
        error_type = "PermissionError"
        field = None
        suggestion = "S3 access denied. Check AWS credentials and IAM permissions for S3 bucket access."

    # Invalid month format
    elif "month" in error_msg and ("invalid" in error_msg or "format" in error_msg):
        error_type = "ConfigError"
        field = "month"
        suggestion = "Month must be in YYYY-MM format (e.g., '2025-09'). Check your config file."

    # No data found for month
    elif "no data" in error_msg or "empty" in error_msg:
        error_type = "DataError"
        field = None
        suggestion = "No data found for the specified month/dataset. Verify previous stages completed successfully and check S3 for expected data."

    # Generic fallback
    if not suggestion:
        suggestion = "Check configuration file for errors. See full traceback below for details."

    return {
        "stage": stage,
        "error_type": error_type,
        "message": str(exception),
        "field": field,
        "suggestion": suggestion,
        "traceback": traceback.format_exc()
    }
