"""
Error message formatters for config errors.

Provides suggestion generators for YAML/TOML config snippets.
"""

from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .context import ConfigErrorContext

from .context import ConfigSourceType


def generate_field_suggestion(
    field_path: list[str],
    context: ConfigErrorContext,
    example_value: str = "..."
) -> str:
    """
    Generate YAML config snippet suggestion for missing field.

    Primary format is YAML. TOML support is deprecated and can be easily removed.

    Args:
        field_path: Path to missing field (e.g., ['connections', 'snowflake', 'passcode'])
        context: Config context (contains source type)
        example_value: Example value to show in snippet

    Returns:
        Config snippet string in YAML format (or TOML if deprecated source)
    """
    # YAML is the primary format
    # TOML support only for deprecated sources (can be easily removed later)
    use_toml = context.source_type in [
        ConfigSourceType.SNOWFLAKE,
        ConfigSourceType.RAICONFIG_TOML
    ]

    if use_toml:
        # DEPRECATED: TOML format support (remove when TOML configs deprecated)
        return _generate_toml_suggestion(field_path, example_value)

    # Primary: YAML format
    return _generate_yaml_suggestion(field_path, example_value)


def _generate_yaml_suggestion(
    field_path: list[str],
    example_value: str
) -> str:
    """
    Generate YAML config snippet (primary format).

    Handles discriminated-union connection paths specially.  Pydantic's `loc`
    for a missing field inside a connection looks like:

        ('connections', '<name>', '<type>', '<authenticator>', '<field>')   # Snowflake
        ('connections', '<name>', '<type>', '<field>')                      # DuckDB/Local

    The intermediate segments (<type>, <authenticator>) are discriminator
    *values*, not YAML keys.  We flatten them into ``type:`` / ``authenticator:``
    fields so the snippet is copy-paste ready.
    """
    lines = ["Add to your raiconfig.yaml:", ""]

    if field_path and field_path[0] == "connections":
        lines.extend(_connection_yaml_lines(field_path, example_value))
    else:
        indent = 0
        for part in field_path:
            lines.append("  " * indent + f"{part}:")
            indent += 1
        lines.append("  " * indent + f'"{example_value}"')

    return "\n".join(lines)


def _connection_yaml_lines(field_path: list[str], example_value: str) -> list[str]:
    """
    Build YAML lines for a connection field path, flattening discriminators.

    Pydantic loc patterns (after 'connections'):
      len 5: connections / conn_name / type_val / auth_val / field  (Snowflake)
      len 4: connections / conn_name / type_val / field             (DuckDB/Local)
    """
    lines: list[str] = []

    if len(field_path) == 5:
        _, conn_name, type_val, auth_val, field = field_path
        lines.append("connections:")
        lines.append(f"  {conn_name}:")
        lines.append(f"    type: {type_val}")
        lines.append(f"    authenticator: {auth_val}")
        lines.append(f'    {field}: "{example_value}"')
    elif len(field_path) == 4:
        _, conn_name, type_val, field = field_path
        lines.append("connections:")
        lines.append(f"  {conn_name}:")
        lines.append(f"    type: {type_val}")
        lines.append(f'    {field}: "{example_value}"')
    else:
        # Unexpected length — fall back to generic nesting
        indent = 0
        for part in field_path:
            lines.append("  " * indent + f"{part}:")
            indent += 1
        lines.append("  " * indent + f'"{example_value}"')

    return lines


# =============================================================================
# DEPRECATED: TOML Support (remove when TOML configs are fully deprecated)
# =============================================================================

def _generate_toml_suggestion(
    field_path: list[str],
    example_value: str
) -> str:
    """
    Generate TOML config snippet (DEPRECATED format).

    This function exists only for backward compatibility with deprecated
    TOML config files. Remove this entire section when TOML support is dropped.

    Args:
        field_path: Path to missing field
        example_value: Example value to show

    Returns:
        TOML config snippet string
    """
    lines = ["Add to your config file:", ""]

    # TOML uses [section.subsection] format
    if len(field_path) > 1:
        section_path = ".".join(field_path[:-1])
        field_name = field_path[-1]
        lines.append(f"[{section_path}]")
        lines.append(f'{field_name} = "{example_value}"')
    else:
        lines.append(f'{field_path[0]} = "{example_value}"')

    return "\n".join(lines)
