"""Validation helpers for ips/sensor - Auto-generated"""

from typing import Any, TypedDict, Literal
from typing_extensions import NotRequired

# 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,
)

# Import central validation functions (avoid duplication across 1,062 files)
from hfortix_fortios._helpers.validation import (
    validate_required_fields as _validate_required_fields,
    validate_enum_field as _validate_enum_field,
    validate_query_parameter as _validate_query_parameter,
)

# ============================================================================
# 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": ["all", "pass", "block"],
        },
        "default-status": {
            "type": "option",
            "help": "Signature default status filter.",
            "default": "all",
            "options": ["all", "enable", "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": ["disable", "enable", "default"],
        },
        "log": {
            "type": "option",
            "help": "Enable/disable logging of signatures included in filter.",
            "default": "enable",
            "options": ["disable", "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": ["disable", "enable"],
        },
        "log-attack-context": {
            "type": "option",
            "help": "Enable/disable logging of attack context: URL buffer, header buffer, body buffer, packet buffer.",
            "default": "disable",
            "options": ["disable", "enable"],
        },
        "action": {
            "type": "option",
            "help": "Action taken with traffic in which signatures are detected.",
            "default": "default",
            "options": ["pass", "block", "reset", "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": ["periodical", "continuous"],
        },
        "rate-track": {
            "type": "option",
            "help": "Track the packet protocol field.",
            "default": "none",
            "options": ["none", "src-ip", "dest-ip", "dhcp-client-mac", "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": ["none", "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": ["disable", "enable"],
        },
    },
}


# Valid enum values from API documentation
VALID_BODY_BLOCK_MALICIOUS_URL = [
    "disable",
    "enable",
]
VALID_BODY_SCAN_BOTNET_CONNECTIONS = [
    "disable",
    "block",
    "monitor",
]
VALID_BODY_EXTENDED_LOG = [
    "enable",
    "disable",
]
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 using central function
    if "action" in params:
        is_valid, error = _validate_query_parameter(
            "action",
            params.get("action"),
            VALID_QUERY_ACTION
        )
        if not is_valid:
            return (False, error)

    return (True, None)


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


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 using central function
    is_valid, error = _validate_required_fields(
        payload,
        REQUIRED_FIELDS,
        FIELD_DESCRIPTIONS
    )
    if not is_valid:
        return (False, error)

    # Step 2: Validate enum values using central function
    if "block-malicious-url" in payload:
        is_valid, error = _validate_enum_field(
            "block-malicious-url",
            payload["block-malicious-url"],
            VALID_BODY_BLOCK_MALICIOUS_URL,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)
    if "scan-botnet-connections" in payload:
        is_valid, error = _validate_enum_field(
            "scan-botnet-connections",
            payload["scan-botnet-connections"],
            VALID_BODY_SCAN_BOTNET_CONNECTIONS,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)
    if "extended-log" in payload:
        is_valid, error = _validate_enum_field(
            "extended-log",
            payload["extended-log"],
            VALID_BODY_EXTENDED_LOG,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)

    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."""
    # Validate enum values using central function
    if "block-malicious-url" in payload:
        is_valid, error = _validate_enum_field(
            "block-malicious-url",
            payload["block-malicious-url"],
            VALID_BODY_BLOCK_MALICIOUS_URL,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)
    if "scan-botnet-connections" in payload:
        is_valid, error = _validate_enum_field(
            "scan-botnet-connections",
            payload["scan-botnet-connections"],
            VALID_BODY_SCAN_BOTNET_CONNECTIONS,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)
    if "extended-log" in payload:
        is_valid, error = _validate_enum_field(
            "extended-log",
            payload["extended-log"],
            VALID_BODY_EXTENDED_LOG,
            FIELD_DESCRIPTIONS
        )
        if not is_valid:
            return (False, error)

    return (True, None)


# ============================================================================
# Metadata Access Functions
# Imported from central module to avoid duplication across 1,062 files
# Bound to this endpoint's data using functools.partial (saves ~7KB per file)
# ============================================================================

from functools import partial
from hfortix_fortios._helpers.metadata import (
    get_field_description,
    get_field_type,
    get_field_constraints,
    get_field_default,
    get_field_options,
    get_nested_schema,
    get_all_fields,
    get_field_metadata,
    validate_field_value,
)

# Bind module-specific data to central functions using partial application
get_field_description = partial(get_field_description, FIELD_DESCRIPTIONS)
get_field_type = partial(get_field_type, FIELD_TYPES)
get_field_constraints = partial(get_field_constraints, FIELD_CONSTRAINTS)
get_field_default = partial(get_field_default, FIELDS_WITH_DEFAULTS)
get_field_options = partial(get_field_options, globals())
get_nested_schema = partial(get_nested_schema, NESTED_SCHEMAS)
get_all_fields = partial(get_all_fields, FIELD_TYPES)
get_field_metadata = partial(get_field_metadata, FIELD_TYPES, FIELD_DESCRIPTIONS, 
                             FIELD_CONSTRAINTS, FIELDS_WITH_DEFAULTS, REQUIRED_FIELDS,
                             NESTED_SCHEMAS, globals())
validate_field_value = partial(validate_field_value, FIELD_TYPES, FIELD_DESCRIPTIONS,
                               FIELD_CONSTRAINTS, globals())


# ============================================================================
# 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()
