"""Validation helpers for ips/sensor - 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 = [
    "name",  # Sensor name.
]

# Fields with defaults (optional)
FIELDS_WITH_DEFAULTS = {
    "name": "",
    "replacemsg-group": "",
    "block-malicious-url": "disable",
    "scan-botnet-connections": "disable",
    "extended-log": "disable",
}

# ============================================================================
# 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",  # Sensor name.
    "comment": "var-string",  # Comment.
    "replacemsg-group": "string",  # Replacement message group.
    "block-malicious-url": "option",  # Enable/disable malicious URL blocking.
    "scan-botnet-connections": "option",  # Block or monitor connections to Botnet servers, or disable B
    "extended-log": "option",  # Enable/disable extended logging.
    "entries": "string",  # IPS sensor filter.
}

# Field descriptions (help text from FortiOS API)
FIELD_DESCRIPTIONS = {
    "name": "Sensor name.",
    "comment": "Comment.",
    "replacemsg-group": "Replacement message group.",
    "block-malicious-url": "Enable/disable malicious URL blocking.",
    "scan-botnet-connections": "Block or monitor connections to Botnet servers, or disable Botnet scanning.",
    "extended-log": "Enable/disable extended logging.",
    "entries": "IPS sensor filter.",
}

# Field constraints (string lengths, integer ranges)
FIELD_CONSTRAINTS = {
    "name": {"type": "string", "max_length": 47},
    "replacemsg-group": {"type": "string", "max_length": 35},
}

# Nested schemas (for table/list fields with children)
NESTED_SCHEMAS = {
    "entries": {
        "id": {
            "type": "integer",
            "help": "Rule ID in IPS database (0 - 4294967295).",
            "default": 0,
            "min_value": 0,
            "max_value": 4294967295,
        },
        "rule": {
            "type": "string",
            "help": "Identifies the predefined or custom IPS signatures to add to the sensor.",
        },
        "location": {
            "type": "user",
            "help": "Protect client or server traffic.",
            "default": "all",
        },
        "severity": {
            "type": "user",
            "help": "Relative severity of the signature, from info to critical. Log messages generated by the signature include the severity.",
            "default": "all",
        },
        "protocol": {
            "type": "user",
            "help": "Protocols to be examined. Use all for every protocol and other for unlisted protocols.",
            "default": "all",
        },
        "os": {
            "type": "user",
            "help": "Operating systems to be protected. Use all for every operating system and other for unlisted operating systems.",
            "default": "all",
        },
        "application": {
            "type": "user",
            "help": "Operating systems to be protected. Use all for every application and other for unlisted application.",
            "default": "all",
        },
        "default-action": {
            "type": "option",
            "help": "Signature default action filter.",
            "default": "all",
            "options": [{"help": "Selects signatures with any default action.", "label": "All", "name": "all"}, {"help": "Selects signatures with default action \u0027pass\u0027.", "label": "Pass", "name": "pass"}, {"help": "Selects signatures with default action \u0027block\u0027.", "label": "Block", "name": "block"}],
        },
        "default-status": {
            "type": "option",
            "help": "Signature default status filter.",
            "default": "all",
            "options": [{"help": "Selects signatures with any default status.", "label": "All", "name": "all"}, {"help": "Selects signatures enabled by default.", "label": "Enable", "name": "enable"}, {"help": "Selects signatures disabled by default.", "label": "Disable", "name": "disable"}],
        },
        "cve": {
            "type": "string",
            "help": "List of CVE IDs of the signatures to add to the sensor.",
        },
        "vuln-type": {
            "type": "string",
            "help": "List of signature vulnerability types to filter by.",
        },
        "last-modified": {
            "type": "user",
            "help": "Filter by signature last modified date. Formats: before <date>, after <date>, between <start-date> <end-date>.",
            "default": "",
        },
        "status": {
            "type": "option",
            "help": "Status of the signatures included in filter. Only those filters with a status to enable are used.",
            "default": "default",
            "options": [{"help": "Disable status of selected rules.", "label": "Disable", "name": "disable"}, {"help": "Enable status of selected rules.", "label": "Enable", "name": "enable"}, {"help": "Default.", "label": "Default", "name": "default"}],
        },
        "log": {
            "type": "option",
            "help": "Enable/disable logging of signatures included in filter.",
            "default": "enable",
            "options": [{"help": "Disable logging of selected rules.", "label": "Disable", "name": "disable"}, {"help": "Enable logging of selected rules.", "label": "Enable", "name": "enable"}],
        },
        "log-packet": {
            "type": "option",
            "help": "Enable/disable packet logging. Enable to save the packet that triggers the filter. You can download the packets in pcap format for diagnostic use.",
            "default": "disable",
            "options": [{"help": "Disable packet logging of selected rules.", "label": "Disable", "name": "disable"}, {"help": "Enable packet logging of selected rules.", "label": "Enable", "name": "enable"}],
        },
        "log-attack-context": {
            "type": "option",
            "help": "Enable/disable logging of attack context: URL buffer, header buffer, body buffer, packet buffer.",
            "default": "disable",
            "options": [{"help": "Disable logging of detailed attack context.", "label": "Disable", "name": "disable"}, {"help": "Enable logging of detailed attack context.", "label": "Enable", "name": "enable"}],
        },
        "action": {
            "type": "option",
            "help": "Action taken with traffic in which signatures are detected.",
            "default": "default",
            "options": [{"help": "Pass or allow matching traffic.", "label": "Pass", "name": "pass"}, {"help": "Block or drop matching traffic.", "label": "Block", "name": "block"}, {"help": "Reset sessions for matching traffic.", "label": "Reset", "name": "reset"}, {"help": "Pass or drop matching traffic, depending on the default action of the signature.", "label": "Default", "name": "default"}],
        },
        "rate-count": {
            "type": "integer",
            "help": "Count of the rate.",
            "default": 0,
            "min_value": 0,
            "max_value": 65535,
        },
        "rate-duration": {
            "type": "integer",
            "help": "Duration (sec) of the rate.",
            "default": 60,
            "min_value": 1,
            "max_value": 65535,
        },
        "rate-mode": {
            "type": "option",
            "help": "Rate limit mode.",
            "default": "continuous",
            "options": [{"help": "Allow configured number of packets every rate-duration.", "label": "Periodical", "name": "periodical"}, {"help": "Block packets once the rate is reached.", "label": "Continuous", "name": "continuous"}],
        },
        "rate-track": {
            "type": "option",
            "help": "Track the packet protocol field.",
            "default": "none",
            "options": [{"help": "none", "label": "None", "name": "none"}, {"help": "Source IP.", "label": "Src Ip", "name": "src-ip"}, {"help": "Destination IP.", "label": "Dest Ip", "name": "dest-ip"}, {"help": "DHCP client.", "label": "Dhcp Client Mac", "name": "dhcp-client-mac"}, {"help": "DNS domain.", "label": "Dns Domain", "name": "dns-domain"}],
        },
        "exempt-ip": {
            "type": "string",
            "help": "Traffic from selected source or destination IP addresses is exempt from this signature.",
        },
        "quarantine": {
            "type": "option",
            "help": "Quarantine method.",
            "default": "none",
            "options": [{"help": "Quarantine is disabled.", "label": "None", "name": "none"}, {"help": "Block all traffic sent from attacker\u0027s IP address. The attacker\u0027s IP address is also added to the banned user list. The target\u0027s address is not affected.", "label": "Attacker", "name": "attacker"}],
        },
        "quarantine-expiry": {
            "type": "user",
            "help": "Duration of quarantine. (Format ###d##h##m, minimum 1m, maximum 364d23h59m, default = 5m). Requires quarantine set to attacker.",
            "default": "5m",
        },
        "quarantine-log": {
            "type": "option",
            "help": "Enable/disable quarantine logging.",
            "default": "enable",
            "options": [{"help": "Disable quarantine logging.", "label": "Disable", "name": "disable"}, {"help": "Enable quarantine logging.", "label": "Enable", "name": "enable"}],
        },
    },
}


# Valid enum values from API documentation
VALID_BODY_BLOCK_MALICIOUS_URL = [
    "disable",  # Disable malicious URL blocking.
    "enable",  # Enable malicious URL blocking.
]
VALID_BODY_SCAN_BOTNET_CONNECTIONS = [
    "disable",  # Do not scan connections to botnet servers.
    "block",  # Block connections to botnet servers.
    "monitor",  # Log connections to botnet servers.
]
VALID_BODY_EXTENDED_LOG = [
    "enable",  # Enable setting.
    "disable",  # Disable setting.
]
VALID_QUERY_ACTION = ["default", "schema"]

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


def validate_ips_sensor_get(
    attr: str | None = None,
    filters: dict[str, Any] | None = None,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate GET request parameters for ips/sensor."""
    # 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 ips/sensor."""
    # 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_ips_sensor_post(
    payload: dict,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate POST request to create new ips/sensor 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 "block-malicious-url" in payload:
        value = payload["block-malicious-url"]
        if value not in VALID_BODY_BLOCK_MALICIOUS_URL:
            desc = FIELD_DESCRIPTIONS.get("block-malicious-url", "")
            error_msg = f"Invalid value for 'block-malicious-url': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_BLOCK_MALICIOUS_URL)}"
            error_msg += f"\n  → Example: block-malicious-url='{{ VALID_BODY_BLOCK_MALICIOUS_URL[0] }}'"
            return (False, error_msg)
    if "scan-botnet-connections" in payload:
        value = payload["scan-botnet-connections"]
        if value not in VALID_BODY_SCAN_BOTNET_CONNECTIONS:
            desc = FIELD_DESCRIPTIONS.get("scan-botnet-connections", "")
            error_msg = f"Invalid value for 'scan-botnet-connections': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_SCAN_BOTNET_CONNECTIONS)}"
            error_msg += f"\n  → Example: scan-botnet-connections='{{ VALID_BODY_SCAN_BOTNET_CONNECTIONS[0] }}'"
            return (False, error_msg)
    if "extended-log" in payload:
        value = payload["extended-log"]
        if value not in VALID_BODY_EXTENDED_LOG:
            desc = FIELD_DESCRIPTIONS.get("extended-log", "")
            error_msg = f"Invalid value for 'extended-log': '{value}'"
            if desc:
                error_msg += f"\n  → Description: {desc}"
            error_msg += f"\n  → Valid options: {', '.join(repr(v) for v in VALID_BODY_EXTENDED_LOG)}"
            error_msg += f"\n  → Example: extended-log='{{ VALID_BODY_EXTENDED_LOG[0] }}'"
            return (False, error_msg)

    return (True, None)


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


def validate_ips_sensor_put(
    payload: dict,
    **params: Any,
) -> tuple[bool, str | None]:
    """Validate PUT request to update ips/sensor."""
    # Step 1: Validate enum values
    if "block-malicious-url" in payload:
        value = payload["block-malicious-url"]
        if value not in VALID_BODY_BLOCK_MALICIOUS_URL:
            return (
                False,
                f"Invalid value for 'block-malicious-url'='{value}'. Must be one of: {', '.join(VALID_BODY_BLOCK_MALICIOUS_URL)}",
            )
    if "scan-botnet-connections" in payload:
        value = payload["scan-botnet-connections"]
        if value not in VALID_BODY_SCAN_BOTNET_CONNECTIONS:
            return (
                False,
                f"Invalid value for 'scan-botnet-connections'='{value}'. Must be one of: {', '.join(VALID_BODY_SCAN_BOTNET_CONNECTIONS)}",
            )
    if "extended-log" in payload:
        value = payload["extended-log"]
        if value not in VALID_BODY_EXTENDED_LOG:
            return (
                False,
                f"Invalid value for 'extended-log'='{value}'. Must be one of: {', '.join(VALID_BODY_EXTENDED_LOG)}",
            )

    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": "ips/sensor",
    "category": "cmdb",
    "api_path": "ips/sensor",
    "mkey": "name",
    "mkey_type": "string",
    "help": "Configure IPS sensor.",
    "total_fields": 7,
    "required_fields_count": 1,
    "fields_with_defaults_count": 5,
}


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