"""Validation helpers for system/pppoe_interface - Auto-generated"""

from typing import Any, TypedDict, NotRequired, Literal

# Import common validators from central _helpers module
from hfortix_fortios._helpers import (
    validate_enable_disable,
    validate_integer_range,
    validate_string_length,
    validate_port_number,
    validate_ip_address,
    validate_ipv6_address,
    validate_mac_address,
)

# ============================================================================
# Required Fields Validation
# Auto-generated from schema
# ============================================================================

# ⚠️  IMPORTANT: FortiOS schemas have known issues with required field marking:

# Do NOT use this list for strict validation - test with the actual FortiOS API!

# Fields marked as required (after filtering false positives)
REQUIRED_FIELDS = [
    "device",  # Name for the physical interface.
]

# Fields with defaults (optional)
FIELDS_WITH_DEFAULTS = {
    "name": "",
    "dial-on-demand": "disable",
    "ipv6": "disable",
    "device": "",
    "username": "",
    "pppoe-egress-cos": "cos0",
    "auth-type": "auto",
    "ipunnumbered": "0.0.0.0",
    "pppoe-unnumbered-negotiate": "enable",
    "idle-timeout": 0,
    "multilink": "disable",
    "mrru": 1500,
    "disc-retry-timeout": 1,
    "padt-retry-timeout": 1,
    "service-name": "",
    "ac-name": "",
    "lcp-echo-interval": 5,
    "lcp-max-echo-fails": 3,
}

# ============================================================================
# Deprecated Fields
# Auto-generated from schema - warns users about deprecated fields
# ============================================================================

# Deprecated fields with migration guidance
DEPRECATED_FIELDS = {
}

# ============================================================================
# Field Metadata (Type Information & Descriptions)
# Auto-generated from schema - use for IDE autocomplete and documentation
# ============================================================================

# Field types mapping
FIELD_TYPES = {
    "name": "string",  # Name of the PPPoE interface.
    "dial-on-demand": "option",  # Enable/disable dial on demand to dial the PPPoE interface wh
    "ipv6": "option",  # Enable/disable IPv6 Control Protocol (IPv6CP).
    "device": "string",  # Name for the physical interface.
    "username": "string",  # User name.
    "password": "password",  # Enter the password.
    "pppoe-egress-cos": "option",  # CoS in VLAN tag for outgoing PPPoE/PPP packets.
    "auth-type": "option",  # PPP authentication type to use.
    "ipunnumbered": "ipv4-address",  # PPPoE unnumbered IP.
    "pppoe-unnumbered-negotiate": "option",  # Enable/disable PPPoE unnumbered negotiation.
    "idle-timeout": "integer",  # PPPoE auto disconnect after idle timeout (0-4294967295 sec).
    "multilink": "option",  # Enable/disable PPP multilink support.
    "mrru": "integer",  # PPP MRRU (296 - 65535, default = 1500).
    "disc-retry-timeout": "integer",  # PPPoE discovery init timeout value in (0-4294967295 sec).
    "padt-retry-timeout": "integer",  # PPPoE terminate timeout value in (0-4294967295 sec).
    "service-name": "string",  # PPPoE service name.
    "ac-name": "string",  # PPPoE AC name.
    "lcp-echo-interval": "integer",  # Time in seconds between PPPoE Link Control Protocol (LCP) ec
    "lcp-max-echo-fails": "integer",  # Maximum missed LCP echo messages before disconnect.
}

# Field descriptions (help text from FortiOS API)
FIELD_DESCRIPTIONS = {
    "name": "Name of the PPPoE interface.",
    "dial-on-demand": "Enable/disable dial on demand to dial the PPPoE interface when packets are routed to the PPPoE interface.",
    "ipv6": "Enable/disable IPv6 Control Protocol (IPv6CP).",
    "device": "Name for the physical interface.",
    "username": "User name.",
    "password": "Enter the password.",
    "pppoe-egress-cos": "CoS in VLAN tag for outgoing PPPoE/PPP packets.",
    "auth-type": "PPP authentication type to use.",
    "ipunnumbered": "PPPoE unnumbered IP.",
    "pppoe-unnumbered-negotiate": "Enable/disable PPPoE unnumbered negotiation.",
    "idle-timeout": "PPPoE auto disconnect after idle timeout (0-4294967295 sec).",
    "multilink": "Enable/disable PPP multilink support.",
    "mrru": "PPP MRRU (296 - 65535, default = 1500).",
    "disc-retry-timeout": "PPPoE discovery init timeout value in (0-4294967295 sec).",
    "padt-retry-timeout": "PPPoE terminate timeout value in (0-4294967295 sec).",
    "service-name": "PPPoE service name.",
    "ac-name": "PPPoE AC name.",
    "lcp-echo-interval": "Time in seconds between PPPoE Link Control Protocol (LCP) echo requests.",
    "lcp-max-echo-fails": "Maximum missed LCP echo messages before disconnect.",
}

# Field constraints (string lengths, integer ranges)
FIELD_CONSTRAINTS = {
    "name": {"type": "string", "max_length": 15},
    "device": {"type": "string", "max_length": 15},
    "username": {"type": "string", "max_length": 64},
    "idle-timeout": {"type": "integer", "min": 0, "max": 4294967295},
    "mrru": {"type": "integer", "min": 296, "max": 65535},
    "disc-retry-timeout": {"type": "integer", "min": 0, "max": 4294967295},
    "padt-retry-timeout": {"type": "integer", "min": 0, "max": 4294967295},
    "service-name": {"type": "string", "max_length": 63},
    "ac-name": {"type": "string", "max_length": 63},
    "lcp-echo-interval": {"type": "integer", "min": 0, "max": 32767},
    "lcp-max-echo-fails": {"type": "integer", "min": 0, "max": 32767},
}

# Nested schemas (for table/list fields with children)
NESTED_SCHEMAS = {
}


# Valid enum values from API documentation
VALID_BODY_DIAL_ON_DEMAND = [
    "enable",  # Enable dial on demand.
    "disable",  # Disable dial on demand.
]
VALID_BODY_IPV6 = [
    "enable",  # Enable IPv6CP.
    "disable",  # Disable IPv6CP.
]
VALID_BODY_PPPOE_EGRESS_COS = [
    "cos0",  # CoS 0.
    "cos1",  # CoS 1.
    "cos2",  # CoS 2.
    "cos3",  # CoS 3.
    "cos4",  # CoS 4.
    "cos5",  # CoS 5.
    "cos6",  # CoS 6.
    "cos7",  # CoS 7.
]
VALID_BODY_AUTH_TYPE = [
    "auto",  # Automatically choose the authentication method.
    "pap",  # PAP authentication.
    "chap",  # CHAP authentication.
    "mschapv1",  # MS-CHAPv1 authentication.
    "mschapv2",  # MS-CHAPv2 authentication.
]
VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE = [
    "enable",  # Enable PPPoE unnumbered negotiation.
    "disable",  # Disable PPPoE unnumbered negotiation.
]
VALID_BODY_MULTILINK = [
    "enable",  # Enable PPP multilink support.
    "disable",  # Disable PPP multilink support.
]
VALID_QUERY_ACTION = ["default", "schema"]

# ============================================================================
# GET Validation
# ============================================================================


def validate_system_pppoe_interface_get(
    attr: str | None = None,
    filters: dict[str, Any] | None = None,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate GET request parameters for system/pppoe_interface."""
    # Validate query parameters if present
    if "action" in params:
        value = params.get("action")
        if value and value not in VALID_QUERY_ACTION:
            return (
                False,
                f"Invalid query parameter 'action'='{value}'. Must be one of: {', '.join(VALID_QUERY_ACTION)}",
            )

    return (True, None)


# ============================================================================
# POST Validation
# ============================================================================


def validate_required_fields(payload: dict) -> tuple[bool, str | None]:
    """Validate required fields for system/pppoe_interface."""
    # Check always-required fields
    missing_fields = []
    for field in REQUIRED_FIELDS:
        if field not in payload:
            missing_fields.append(field)
    
    if missing_fields:
        # Build enhanced error message
        error_parts = [f"Missing required field(s): {', '.join(missing_fields)}"]
        
        # Add descriptions for first few missing fields
        for field in missing_fields[:3]:
            desc = FIELD_DESCRIPTIONS.get(field)
            if desc:
                error_parts.append(f"  • {field}: {desc}")
        
        if len(missing_fields) > 3:
            error_parts.append(f"  ... and {len(missing_fields) - 3} more")
        
        return (False, "\n".join(error_parts))

    return (True, None)


def validate_system_pppoe_interface_post(
    payload: dict,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate POST request to create new system/pppoe_interface object."""
    # Step 1: Validate required fields
    is_valid, error = validate_required_fields(payload)
    if not is_valid:
        return (False, error)

    # Step 2: Validate enum values
    if "dial-on-demand" in payload:
        value = payload["dial-on-demand"]
        if value not in VALID_BODY_DIAL_ON_DEMAND:
            desc = FIELD_DESCRIPTIONS.get("dial-on-demand", "")
            error_msg = f"Invalid value for 'dial-on-demand': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_DIAL_ON_DEMAND)}"
            error_msg += f"\n  → Example: dial-on-demand='{{ VALID_BODY_DIAL_ON_DEMAND[0] }}'"
            return (False, error_msg)
    if "ipv6" in payload:
        value = payload["ipv6"]
        if value not in VALID_BODY_IPV6:
            desc = FIELD_DESCRIPTIONS.get("ipv6", "")
            error_msg = f"Invalid value for 'ipv6': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_IPV6)}"
            error_msg += f"\n  → Example: ipv6='{{ VALID_BODY_IPV6[0] }}'"
            return (False, error_msg)
    if "pppoe-egress-cos" in payload:
        value = payload["pppoe-egress-cos"]
        if value not in VALID_BODY_PPPOE_EGRESS_COS:
            desc = FIELD_DESCRIPTIONS.get("pppoe-egress-cos", "")
            error_msg = f"Invalid value for 'pppoe-egress-cos': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_PPPOE_EGRESS_COS)}"
            error_msg += f"\n  → Example: pppoe-egress-cos='{{ VALID_BODY_PPPOE_EGRESS_COS[0] }}'"
            return (False, error_msg)
    if "auth-type" in payload:
        value = payload["auth-type"]
        if value not in VALID_BODY_AUTH_TYPE:
            desc = FIELD_DESCRIPTIONS.get("auth-type", "")
            error_msg = f"Invalid value for 'auth-type': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_AUTH_TYPE)}"
            error_msg += f"\n  → Example: auth-type='{{ VALID_BODY_AUTH_TYPE[0] }}'"
            return (False, error_msg)
    if "pppoe-unnumbered-negotiate" in payload:
        value = payload["pppoe-unnumbered-negotiate"]
        if value not in VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE:
            desc = FIELD_DESCRIPTIONS.get("pppoe-unnumbered-negotiate", "")
            error_msg = f"Invalid value for 'pppoe-unnumbered-negotiate': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE)}"
            error_msg += f"\n  → Example: pppoe-unnumbered-negotiate='{{ VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE[0] }}'"
            return (False, error_msg)
    if "multilink" in payload:
        value = payload["multilink"]
        if value not in VALID_BODY_MULTILINK:
            desc = FIELD_DESCRIPTIONS.get("multilink", "")
            error_msg = f"Invalid value for 'multilink': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_MULTILINK)}"
            error_msg += f"\n  → Example: multilink='{{ VALID_BODY_MULTILINK[0] }}'"
            return (False, error_msg)

    return (True, None)


# ============================================================================
# PUT Validation
# ============================================================================


def validate_system_pppoe_interface_put(
    payload: dict,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate PUT request to update system/pppoe_interface."""
    # Step 1: Validate enum values
    if "dial-on-demand" in payload:
        value = payload["dial-on-demand"]
        if value not in VALID_BODY_DIAL_ON_DEMAND:
            return (
                False,
                f"Invalid value for 'dial-on-demand'='{value}'. Must be one of: {', '.join(VALID_BODY_DIAL_ON_DEMAND)}",
            )
    if "ipv6" in payload:
        value = payload["ipv6"]
        if value not in VALID_BODY_IPV6:
            return (
                False,
                f"Invalid value for 'ipv6'='{value}'. Must be one of: {', '.join(VALID_BODY_IPV6)}",
            )
    if "pppoe-egress-cos" in payload:
        value = payload["pppoe-egress-cos"]
        if value not in VALID_BODY_PPPOE_EGRESS_COS:
            return (
                False,
                f"Invalid value for 'pppoe-egress-cos'='{value}'. Must be one of: {', '.join(VALID_BODY_PPPOE_EGRESS_COS)}",
            )
    if "auth-type" in payload:
        value = payload["auth-type"]
        if value not in VALID_BODY_AUTH_TYPE:
            return (
                False,
                f"Invalid value for 'auth-type'='{value}'. Must be one of: {', '.join(VALID_BODY_AUTH_TYPE)}",
            )
    if "pppoe-unnumbered-negotiate" in payload:
        value = payload["pppoe-unnumbered-negotiate"]
        if value not in VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE:
            return (
                False,
                f"Invalid value for 'pppoe-unnumbered-negotiate'='{value}'. Must be one of: {', '.join(VALID_BODY_PPPOE_UNNUMBERED_NEGOTIATE)}",
            )
    if "multilink" in payload:
        value = payload["multilink"]
        if value not in VALID_BODY_MULTILINK:
            return (
                False,
                f"Invalid value for 'multilink'='{value}'. Must be one of: {', '.join(VALID_BODY_MULTILINK)}",
            )

    return (True, None)


# ============================================================================
# Metadata Access Functions
# Imported from central module to avoid duplication across 1,062 files
# ============================================================================

from hfortix_fortios._helpers.metadata import (
    get_field_description as _get_field_description,
    get_field_type as _get_field_type,
    get_field_constraints as _get_field_constraints,
    get_field_default as _get_field_default,
    get_field_options as _get_field_options,
    get_nested_schema as _get_nested_schema,
    get_all_fields as _get_all_fields,
    get_field_metadata as _get_field_metadata,
    validate_field_value as _validate_field_value,
)

# Wrapper functions that bind module-specific data to central functions
def get_field_description(field_name: str) -> str | None:
    """Get description/help text for a field."""
    return _get_field_description(FIELD_DESCRIPTIONS, field_name)

def get_field_type(field_name: str) -> str | None:
    """Get the type of a field."""
    return _get_field_type(FIELD_TYPES, field_name)

def get_field_constraints(field_name: str) -> dict[str, Any] | None:
    """Get constraints for a field (min/max values, string length)."""
    return _get_field_constraints(FIELD_CONSTRAINTS, field_name)

def get_field_default(field_name: str) -> Any | None:
    """Get default value for a field."""
    return _get_field_default(FIELDS_WITH_DEFAULTS, field_name)

def get_field_options(field_name: str) -> list[str] | None:
    """Get valid enum options for a field."""
    return _get_field_options(globals(), field_name)

def get_nested_schema(field_name: str) -> dict[str, Any] | None:
    """Get schema for nested table/list fields."""
    return _get_nested_schema(NESTED_SCHEMAS, field_name)

def get_all_fields() -> list[str]:
    """Get list of all field names."""
    return _get_all_fields(FIELD_TYPES)

def get_field_metadata(field_name: str) -> dict[str, Any] | None:
    """Get complete metadata for a field (type, description, constraints, defaults, options)."""
    return _get_field_metadata(
        FIELD_TYPES, FIELD_DESCRIPTIONS, FIELD_CONSTRAINTS,
        FIELDS_WITH_DEFAULTS, REQUIRED_FIELDS, NESTED_SCHEMAS,
        globals(), field_name
    )

def validate_field_value(field_name: str, value: Any) -> tuple[bool, str | None]:
    """Validate a single field value against its constraints."""
    return _validate_field_value(
        FIELD_TYPES, FIELD_DESCRIPTIONS, FIELD_CONSTRAINTS,
        globals(), field_name, value
    )


# ============================================================================
# Schema Information
# Metadata about this endpoint schema
# ============================================================================

SCHEMA_INFO = {
    "endpoint": "system/pppoe_interface",
    "category": "cmdb",
    "api_path": "system/pppoe-interface",
    "mkey": "name",
    "mkey_type": "string",
    "help": "Configure the PPPoE interfaces.",
    "total_fields": 19,
    "required_fields_count": 1,
    "fields_with_defaults_count": 18,
}


def get_schema_info() -> dict[str, Any]:
    """Get information about this endpoint schema."""
    return SCHEMA_INFO.copy()
