"""Fallback description generation for the Gemini client.

This module provides fallback functionality when the Gemini API is unavailable
or fails to generate a proper response.
"""

from exc2issue.core.models import ErrorRecord


def create_fallback_description(error_record: ErrorRecord) -> str:
    """Create fallback description when AI generation fails.

    This is the most resilient version combining the best parts from both
    the original gemini_client.py and decorator.py implementations.

    Args:
        error_record: ErrorRecord containing error details

    Returns:
        Fallback description string
    """
    parts = [
        f"# Error in function: {error_record.function_name}",
        "",
        f"**Error Type:** {error_record.error_type}",
        f"**Error Message:** {error_record.error_message}",
        "",
    ]

    # Handle function arguments (both positional args and kwargs)
    if error_record.function_args:
        parts.extend(
            [
                "**Function Arguments:**",
                f"```\n{error_record.function_args}\n```",
                "",
            ]
        )

    # Handle function keyword arguments if available
    if hasattr(error_record, "function_kwargs") and error_record.function_kwargs:
        parts.extend(
            [
                "**Function Keyword Arguments:**",
                f"```\n{error_record.function_kwargs}\n```",
                "",
            ]
        )

    # Handle traceback with proper validation
    if error_record.traceback and error_record.traceback.strip():
        parts.extend(
            [
                "**Stack Trace:**",
                f"```\n{error_record.traceback}\n```",
                "",
            ]
        )

    # Add timestamp if available
    if error_record.timestamp:
        parts.extend([f"**Timestamp:** {error_record.timestamp.isoformat()}", ""])

    # Add footer
    parts.extend(
        [
            "---",
            "*This issue was automatically generated by exc2issue "
            "(AI generation unavailable)*",
        ]
    )

    return "\n".join(parts)
