# lightwave/schema/pydantic/middleware/middleware.py
"""
Pydantic schemas for middleware.yaml validation.

This module provides typed configuration for the Django middleware stack,
including tenant resolution, security, rate limiting, and authentication.

SST File: lightwave/schema/definitions/middleware.yaml

Usage:
    from lightwave.schema.pydantic.contracts.middleware import MiddlewareConfig, get_middleware_config

    config = get_middleware_config()
    stack = config.get_middleware_stack()
    print(f"Middleware stack has {len(stack)} entries")

    # Get middleware by phase
    security_middleware = config.get_middleware_by_phase("security")
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, ClassVar, Literal

import yaml
from pydantic import Field

from lightwave.schema.pydantic.core.base import LightwaveBaseSchema, SSTSchema

# =============================================================================
# LITERAL TYPES (match YAML enums)
# =============================================================================

MiddlewarePhase = Literal[
    "tenant_resolution",
    "security",
    "request_processing",
    "authentication",
    "rate_limiting",
    "feature_flags",
    "context",
    "monitoring",
]

ResolutionStrategy = Literal["domain", "header", "path"]

UnknownDomainAction = Literal["redirect", "404", "default_tenant"]

RateLimitBackendType = Literal["redis", "memory", "database"]

LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR"]

EnvironmentName = Literal["development", "staging", "production"]


# =============================================================================
# MIDDLEWARE STACK SCHEMAS
# =============================================================================


class MiddlewareStackEntry(LightwaveBaseSchema):
    """Individual middleware entry in the stack."""

    middleware: str = Field(..., description="Full dotted path to middleware class")
    phase: MiddlewarePhase = Field(..., description="Middleware phase")
    order: int = Field(..., ge=1, le=100, description="Execution order within phase")
    description: str = Field(..., description="What this middleware does")
    required: bool = Field(True, description="Whether middleware is required")
    environments: list[EnvironmentName] | None = Field(None, description="Environments where this middleware is active")
    feature_flag: str | None = Field(None, description="Feature flag that enables this middleware")
    config_ref: str | None = Field(None, description="Reference to configuration section")


# =============================================================================
# TENANT MIDDLEWARE SCHEMAS
# =============================================================================


class TenantResolutionConfig(LightwaveBaseSchema):
    """Domain resolution strategy configuration."""

    strategy: ResolutionStrategy = Field("domain", description="Resolution strategy")
    fallback_tenant: str = Field("public", description="Fallback tenant schema")
    cache_tenant_lookup: bool = Field(True, description="Cache tenant lookups")
    cache_ttl_seconds: int = Field(300, ge=0, description="Cache TTL in seconds")


class DomainMatchingConfig(LightwaveBaseSchema):
    """Domain matching rules."""

    case_sensitive: bool = Field(False, description="Case-sensitive domain matching")
    strip_www: bool = Field(True, description="Strip www prefix from domains")
    support_wildcards: bool = Field(True, description="Support wildcard domains")
    wildcard_pattern: str = Field("*.{base_domain}", description="Wildcard pattern template")


class TenantContextConfig(LightwaveBaseSchema):
    """Tenant context enrichment settings."""

    load_features: bool = Field(True, description="Load tenant features")
    load_settings: bool = Field(True, description="Load tenant settings")
    load_brand: bool = Field(True, description="Load tenant brand config")
    inject_into_request: bool = Field(True, description="Inject context into request")
    attribute_name: str = Field("tenant_context", description="Request attribute name for context")


class TenantSchemaConfig(LightwaveBaseSchema):
    """PostgreSQL schema switching settings."""

    auto_switch: bool = Field(True, description="Auto-switch to tenant schema")
    verify_schema_exists: bool = Field(True, description="Verify schema exists")
    create_missing_schemas: bool = Field(False, description="Create missing schemas (dev only)")


class TenantErrorConfig(LightwaveBaseSchema):
    """Tenant resolution error handling."""

    unknown_domain_action: UnknownDomainAction = Field("redirect", description="Action for unknown domains")
    unknown_domain_redirect: str = Field("https://lightwave-media.ltd", description="Redirect URL for unknown domains")
    log_resolution_failures: bool = Field(True, description="Log resolution failures")


class TenantMiddlewareConfig(LightwaveBaseSchema):
    """Complete tenant middleware configuration."""

    resolution: TenantResolutionConfig = Field(
        default_factory=TenantResolutionConfig, description="Resolution settings"
    )
    domain_matching: DomainMatchingConfig = Field(
        default_factory=DomainMatchingConfig, description="Domain matching rules"
    )
    context: TenantContextConfig = Field(default_factory=TenantContextConfig, description="Context enrichment")
    schema_config: TenantSchemaConfig = Field(
        default_factory=TenantSchemaConfig,
        alias="schema",
        description="Schema switching",
    )
    errors: TenantErrorConfig = Field(default_factory=TenantErrorConfig, description="Error handling")


# =============================================================================
# SECURITY MIDDLEWARE SCHEMAS
# =============================================================================


class HTTPSConfig(LightwaveBaseSchema):
    """HTTPS enforcement settings."""

    redirect_enabled: bool = Field(True, description="Enable HTTPS redirect")
    redirect_exempt_paths: list[str] = Field(default_factory=list, description="Paths exempt from HTTPS redirect")
    hsts_enabled: bool = Field(True, description="Enable HSTS header")
    hsts_seconds: int = Field(31536000, ge=0, description="HSTS max-age in seconds")
    hsts_include_subdomains: bool = Field(True, description="Include subdomains in HSTS")
    hsts_preload: bool = Field(True, description="Enable HSTS preload")


class CSPOverride(LightwaveBaseSchema):
    """Content Security Policy override per tenant."""

    frame_src: list[str] | None = Field(None, description="frame-src directive")
    media_src: list[str] | None = Field(None, description="media-src directive")
    script_src: list[str] | None = Field(None, description="script-src directive")
    connect_src: list[str] | None = Field(None, description="connect-src directive")
    style_src: list[str] | None = Field(None, description="style-src directive")
    img_src: list[str] | None = Field(None, description="img-src directive")


class RequestValidationConfig(LightwaveBaseSchema):
    """Request validation settings."""

    max_content_length_mb: int = Field(50, ge=1, description="Max content length in MB")
    allowed_content_types: list[str] = Field(default_factory=list, description="Allowed content types")
    block_suspicious_paths: bool = Field(True, description="Block suspicious paths")
    suspicious_patterns: list[str] = Field(default_factory=list, description="Suspicious path patterns to block")


class SecurityMiddlewareConfig(LightwaveBaseSchema):
    """Complete security middleware configuration."""

    https: HTTPSConfig = Field(default_factory=HTTPSConfig, description="HTTPS settings")
    csp_overrides: dict[str, CSPOverride] = Field(default_factory=dict, description="Per-tenant CSP overrides")
    request_validation: RequestValidationConfig = Field(
        default_factory=RequestValidationConfig, description="Request validation"
    )


# =============================================================================
# RATE LIMIT MIDDLEWARE SCHEMAS
# =============================================================================


class RateLimitBackendConfig(LightwaveBaseSchema):
    """Rate limit storage backend configuration."""

    type: RateLimitBackendType = Field("redis", description="Backend type")
    redis_url: str = Field("${REDIS_URL}", description="Redis connection URL")
    key_prefix: str = Field("lw_ratelimit", description="Key prefix for rate limits")


class ClientIdentificationConfig(LightwaveBaseSchema):
    """Client identification for rate limiting."""

    methods: list[str] = Field(
        default_factory=lambda: ["api_key", "user_id", "ip_address"],
        description="Identification methods in priority order",
    )
    trust_proxy_headers: bool = Field(True, description="Trust proxy headers")
    proxy_header: str = Field("X-Forwarded-For", description="Proxy header name")
    proxy_count: int = Field(1, ge=0, description="Number of proxies to trust")


class RateLimitResponseConfig(LightwaveBaseSchema):
    """Rate limit response configuration."""

    status_code: int = Field(429, description="HTTP status code for rate limit")
    include_retry_after: bool = Field(True, description="Include Retry-After header")
    include_limit_headers: bool = Field(True, description="Include rate limit headers")
    headers: dict[str, str] = Field(
        default_factory=lambda: {
            "limit": "X-RateLimit-Limit",
            "remaining": "X-RateLimit-Remaining",
            "reset": "X-RateLimit-Reset",
        },
        description="Rate limit header names",
    )


class RateLimitExemptionsConfig(LightwaveBaseSchema):
    """Rate limit exemption rules."""

    paths: list[str] = Field(default_factory=list, description="Exempt paths")
    user_roles: list[str] = Field(default_factory=list, description="Exempt user roles")
    api_key_types: list[str] = Field(default_factory=list, description="Exempt API key types")


class TenantRateLimitOverride(LightwaveBaseSchema):
    """Per-tenant rate limit override."""

    multiplier: float | None = Field(None, ge=0, description="Rate limit multiplier")
    enabled: bool = Field(True, description="Whether rate limiting is enabled")


class RateLimitMiddlewareConfig(LightwaveBaseSchema):
    """Complete rate limit middleware configuration."""

    backend: RateLimitBackendConfig = Field(default_factory=RateLimitBackendConfig, description="Storage backend")
    client_identification: ClientIdentificationConfig = Field(
        default_factory=ClientIdentificationConfig, description="Client identification"
    )
    response: RateLimitResponseConfig = Field(default_factory=RateLimitResponseConfig, description="Response settings")
    exemptions: RateLimitExemptionsConfig = Field(
        default_factory=RateLimitExemptionsConfig, description="Exemption rules"
    )
    tenant_overrides: dict[str, TenantRateLimitOverride] = Field(
        default_factory=dict, description="Per-tenant overrides"
    )


# =============================================================================
# AUTHENTICATION MIDDLEWARE SCHEMAS
# =============================================================================


class CrossTenantAuthConfig(LightwaveBaseSchema):
    """Cross-tenant authentication settings."""

    enabled: bool = Field(True, description="Enable cross-tenant auth")
    shared_session_domains: list[str] = Field(default_factory=list, description="Domains that share sessions")
    session_cookie_domain: str | None = Field(None, description="Session cookie domain")


class SSOConfig(LightwaveBaseSchema):
    """SSO configuration."""

    enabled_tenants: list[str] = Field(default_factory=list, description="Tenants with SSO enabled")
    provider: str = Field("google", description="SSO provider")
    auto_create_user: bool = Field(False, description="Auto-create users from SSO")
    required_email_domains: list[str] = Field(default_factory=list, description="Required email domains for SSO")


class APIAuthConfig(LightwaveBaseSchema):
    """API authentication configuration."""

    auth_header: str = Field("Authorization", description="Auth header name")
    auth_scheme: str = Field("Bearer", description="Auth scheme")
    api_key_header: str = Field("X-Agent-Key", description="API key header")
    validate_on_every_request: bool = Field(True, description="Validate auth on every request")


class AuthMiddlewareConfig(LightwaveBaseSchema):
    """Complete authentication middleware configuration."""

    session: dict[str, Any] = Field(
        default_factory=lambda: {"config_ref": "security.sessions"},
        description="Session config reference",
    )
    cross_tenant: CrossTenantAuthConfig = Field(default_factory=CrossTenantAuthConfig, description="Cross-tenant auth")
    sso: SSOConfig = Field(default_factory=SSOConfig, description="SSO settings")
    api: APIAuthConfig = Field(default_factory=APIAuthConfig, description="API auth")


# =============================================================================
# LOGGING MIDDLEWARE SCHEMAS
# =============================================================================


class LoggingMiddlewareConfig(LightwaveBaseSchema):
    """Request/response logging configuration."""

    # What to log
    log_requests: bool = Field(True, description="Log incoming requests")
    log_responses: bool = Field(True, description="Log outgoing responses")
    log_headers: bool = Field(False, description="Log request headers")
    log_body: bool = Field(False, description="Log request body")

    # Filtering
    exclude_paths: list[str] = Field(default_factory=list, description="Paths to exclude from logging")
    exclude_methods: list[str] = Field(default_factory=list, description="HTTP methods to exclude")

    # Sensitive data
    sensitive_headers: list[str] = Field(default_factory=list, description="Headers to redact")
    redact_sensitive: bool = Field(True, description="Redact sensitive data")
    redaction_string: str = Field("[REDACTED]", description="Redaction placeholder")

    # Performance
    log_timing: bool = Field(True, description="Log request timing")
    slow_request_threshold_ms: int = Field(1000, ge=0, description="Threshold for slow request warning (ms)")

    # Output
    logger_name: str = Field("lightwave.requests", description="Logger name")
    log_level: LogLevel = Field("INFO", description="Log level")
    structured_logging: bool = Field(True, description="Use structured logging")


# =============================================================================
# ENVIRONMENT CONFIGURATION SCHEMAS
# =============================================================================


class DebugToolbarConfig(LightwaveBaseSchema):
    """Django Debug Toolbar configuration."""

    enabled: bool = Field(False, description="Enable debug toolbar")
    middleware: str = Field(
        "debug_toolbar.middleware.DebugToolbarMiddleware",
        description="Debug toolbar middleware path",
    )
    position: int = Field(5, ge=1, description="Position in middleware stack")
    internal_ips: list[str] = Field(
        default_factory=lambda: ["127.0.0.1", "localhost"],
        description="Internal IPs for debug toolbar",
    )


class EnvironmentCORSConfig(LightwaveBaseSchema):
    """Per-environment CORS configuration."""

    allow_all_origins: bool = Field(False, description="Allow all origins")


class EnvironmentRateLimitConfig(LightwaveBaseSchema):
    """Per-environment rate limit configuration."""

    enabled: bool = Field(True, description="Enable rate limiting")
    multiplier: float = Field(1.0, ge=0, description="Rate limit multiplier")
    strict_mode: bool = Field(False, description="Enable strict mode")


class EnvironmentConfig(LightwaveBaseSchema):
    """Per-environment middleware configuration."""

    debug_toolbar: DebugToolbarConfig | None = Field(None, description="Debug toolbar config")
    cors: EnvironmentCORSConfig = Field(default_factory=EnvironmentCORSConfig, description="CORS config")
    rate_limiting: EnvironmentRateLimitConfig = Field(
        default_factory=EnvironmentRateLimitConfig, description="Rate limiting config"
    )


# =============================================================================
# HEALTH CHECK SCHEMAS
# =============================================================================


class OrderValidationConfig(LightwaveBaseSchema):
    """Middleware order validation rules."""

    enabled: bool = Field(True, description="Enable order validation")
    rules: list[str] = Field(default_factory=list, description="Order validation rules")


class PerformanceMonitoringConfig(LightwaveBaseSchema):
    """Middleware performance monitoring."""

    track_middleware_timing: bool = Field(True, description="Track middleware timing")
    alert_threshold_ms: int = Field(50, ge=0, description="Per-middleware alert threshold (ms)")
    total_threshold_ms: int = Field(200, ge=0, description="Total chain threshold (ms)")


class StartupChecksConfig(LightwaveBaseSchema):
    """Middleware startup validation checks."""

    verify_all_middleware_importable: bool = Field(True, description="Verify all middleware can be imported")
    verify_config_refs_exist: bool = Field(True, description="Verify config references exist")
    log_final_stack: bool = Field(True, description="Log final middleware stack")


class HealthChecksConfig(LightwaveBaseSchema):
    """Middleware health check configuration."""

    order_validation: OrderValidationConfig = Field(
        default_factory=OrderValidationConfig, description="Order validation"
    )
    performance: PerformanceMonitoringConfig = Field(
        default_factory=PerformanceMonitoringConfig, description="Performance monitoring"
    )
    startup: StartupChecksConfig = Field(default_factory=StartupChecksConfig, description="Startup checks")


# =============================================================================
# MAIN MIDDLEWARE CONFIG
# =============================================================================


class MiddlewareConfigMeta(LightwaveBaseSchema):
    """Metadata for middleware configuration."""

    version: str = Field(..., description="Schema version")
    model: str | None = Field(None, description="Database model (null for config-only)")
    description: str = Field(..., description="Configuration description")


class MiddlewareConfig(SSTSchema):
    """
    Complete middleware configuration from middleware.yaml.

    Provides typed access to the entire middleware stack configuration:
    - Middleware stack entries with ordering
    - Tenant resolution settings
    - Security middleware settings
    - Rate limiting configuration
    - Authentication settings
    - Logging configuration
    - Per-environment overrides
    - Health check configuration

    Example:
        config = MiddlewareConfig.load()
        stack = config.get_middleware_stack()
        for entry in stack:
            print(f"{entry.order}: {entry.middleware}")

    SST Validation:
        config = MiddlewareConfig.load()
        assert len(config.middleware_stack) > 0
        assert config.tenant_middleware.resolution.strategy == "domain"
    """

    SST_KEY: ClassVar[str] = "middleware"  # Registry key in __index.yaml

    # Metadata
    meta: MiddlewareConfigMeta = Field(..., alias="_meta", description="Configuration metadata")

    # Middleware stack
    middleware_stack: list[MiddlewareStackEntry] = Field(default_factory=list, description="Ordered middleware stack")

    # Section configurations
    tenant_middleware: TenantMiddlewareConfig = Field(
        default_factory=TenantMiddlewareConfig, description="Tenant middleware config"
    )
    security_middleware: SecurityMiddlewareConfig = Field(
        default_factory=SecurityMiddlewareConfig, description="Security middleware config"
    )
    rate_limit_middleware: RateLimitMiddlewareConfig = Field(
        default_factory=RateLimitMiddlewareConfig, description="Rate limit config"
    )
    auth_middleware: AuthMiddlewareConfig = Field(
        default_factory=AuthMiddlewareConfig, description="Auth middleware config"
    )
    logging_middleware: LoggingMiddlewareConfig = Field(
        default_factory=LoggingMiddlewareConfig, description="Logging config"
    )

    # Environment configs
    environments: dict[EnvironmentName, EnvironmentConfig] = Field(
        default_factory=dict, description="Per-environment configs"
    )

    # Health checks
    health_checks: HealthChecksConfig = Field(default_factory=HealthChecksConfig, description="Health check config")

    @classmethod
    def get_sst_path(cls) -> Path:
        """Get path to SST YAML file (from __index.yaml registry)."""
        from lightwave.schema.core.paths import get_sst_path

        return get_sst_path(cls.SST_KEY)

    @classmethod
    def load_sst_data(cls) -> dict[str, Any]:
        """Load SST YAML file."""
        sst_path = cls.get_sst_path()
        if not sst_path.exists():
            raise FileNotFoundError(f"SST file not found: {sst_path}")
        with open(sst_path) as f:
            return yaml.safe_load(f)

    @classmethod
    def load(cls) -> "MiddlewareConfig":
        """
        Load middleware configuration from SST YAML.

        Returns:
            MiddlewareConfig instance
        """
        data = cls.load_sst_data()

        # Parse middleware stack
        middleware_stack = []
        for entry in data.get("middleware_stack", []):
            middleware_stack.append(MiddlewareStackEntry(**entry))

        # Parse tenant middleware
        tenant_raw = data.get("tenant_middleware", {})
        tenant_middleware = TenantMiddlewareConfig(
            resolution=TenantResolutionConfig(**tenant_raw.get("resolution", {})),
            domain_matching=DomainMatchingConfig(**tenant_raw.get("domain_matching", {})),
            context=TenantContextConfig(**tenant_raw.get("context", {})),
            schema_config=TenantSchemaConfig(**tenant_raw.get("schema", {})),
            errors=TenantErrorConfig(**tenant_raw.get("errors", {})),
        )

        # Parse security middleware
        security_raw = data.get("security_middleware", {})
        csp_overrides = {}
        for tenant, csp_data in security_raw.get("csp_overrides", {}).items():
            csp_overrides[tenant] = CSPOverride(**csp_data)
        security_middleware = SecurityMiddlewareConfig(
            https=HTTPSConfig(**security_raw.get("https", {})),
            csp_overrides=csp_overrides,
            request_validation=RequestValidationConfig(**security_raw.get("request_validation", {})),
        )

        # Parse rate limit middleware
        rate_raw = data.get("rate_limit_middleware", {})
        tenant_overrides = {}
        for tenant, override_data in rate_raw.get("tenant_overrides", {}).items():
            tenant_overrides[tenant] = TenantRateLimitOverride(**override_data)
        rate_limit_middleware = RateLimitMiddlewareConfig(
            backend=RateLimitBackendConfig(**rate_raw.get("backend", {})),
            client_identification=ClientIdentificationConfig(**rate_raw.get("client_identification", {})),
            response=RateLimitResponseConfig(**rate_raw.get("response", {})),
            exemptions=RateLimitExemptionsConfig(**rate_raw.get("exemptions", {})),
            tenant_overrides=tenant_overrides,
        )

        # Parse auth middleware
        auth_raw = data.get("auth_middleware", {})
        auth_middleware = AuthMiddlewareConfig(
            session=auth_raw.get("session", {}),
            cross_tenant=CrossTenantAuthConfig(**auth_raw.get("cross_tenant", {})),
            sso=SSOConfig(**auth_raw.get("sso", {})),
            api=APIAuthConfig(**auth_raw.get("api", {})),
        )

        # Parse logging middleware
        logging_raw = data.get("logging_middleware", {})
        logging_middleware = LoggingMiddlewareConfig(**logging_raw)

        # Parse environment configs
        environments: dict[EnvironmentName, EnvironmentConfig] = {}
        for env_name, env_data in data.get("environments", {}).items():
            debug_toolbar = None
            if "debug_toolbar" in env_data:
                debug_toolbar = DebugToolbarConfig(**env_data["debug_toolbar"])
            environments[env_name] = EnvironmentConfig(  # type: ignore[index]
                debug_toolbar=debug_toolbar,
                cors=EnvironmentCORSConfig(**env_data.get("cors", {})),
                rate_limiting=EnvironmentRateLimitConfig(**env_data.get("rate_limiting", {})),
            )

        # Parse health checks
        health_raw = data.get("health_checks", {})
        health_checks = HealthChecksConfig(
            order_validation=OrderValidationConfig(**health_raw.get("order_validation", {})),
            performance=PerformanceMonitoringConfig(**health_raw.get("performance", {})),
            startup=StartupChecksConfig(**health_raw.get("startup", {})),
        )

        return cls(
            _meta=MiddlewareConfigMeta(**data.get("_meta", {})),
            middleware_stack=middleware_stack,
            tenant_middleware=tenant_middleware,
            security_middleware=security_middleware,
            rate_limit_middleware=rate_limit_middleware,
            auth_middleware=auth_middleware,
            logging_middleware=logging_middleware,
            environments=environments,
            health_checks=health_checks,
        )

    def get_middleware_stack(self, environment: EnvironmentName | None = None) -> list[MiddlewareStackEntry]:
        """
        Get the middleware stack, optionally filtered by environment.

        Args:
            environment: Optional environment filter

        Returns:
            List of middleware entries sorted by order
        """
        stack = []
        for entry in sorted(self.middleware_stack, key=lambda e: e.order):
            # Filter by environment if specified
            if environment and entry.environments:
                if environment not in entry.environments:
                    continue
            stack.append(entry)
        return stack

    def get_middleware_by_phase(self, phase: MiddlewarePhase) -> list[MiddlewareStackEntry]:
        """
        Get all middleware in a specific phase.

        Args:
            phase: The middleware phase

        Returns:
            List of middleware entries in that phase
        """
        return [entry for entry in sorted(self.middleware_stack, key=lambda e: e.order) if entry.phase == phase]

    def get_middleware_paths(self, environment: EnvironmentName | None = None) -> list[str]:
        """
        Get list of middleware dotted paths for Django MIDDLEWARE setting.

        Args:
            environment: Optional environment filter

        Returns:
            List of middleware paths in correct order
        """
        stack = self.get_middleware_stack(environment)
        return [entry.middleware for entry in stack if entry.required or environment]

    def get_csp_override(self, tenant_slug: str) -> CSPOverride | None:
        """
        Get CSP override for a specific tenant.

        Args:
            tenant_slug: Tenant identifier

        Returns:
            CSPOverride if configured, None otherwise
        """
        return self.security_middleware.csp_overrides.get(tenant_slug)

    def get_rate_limit_override(self, tenant_slug: str) -> TenantRateLimitOverride | None:
        """
        Get rate limit override for a specific tenant.

        Args:
            tenant_slug: Tenant identifier

        Returns:
            TenantRateLimitOverride if configured, None otherwise
        """
        return self.rate_limit_middleware.tenant_overrides.get(tenant_slug)

    def is_path_exempt_from_https(self, path: str) -> bool:
        """
        Check if a path is exempt from HTTPS redirect.

        Args:
            path: Request path

        Returns:
            True if exempt, False otherwise
        """
        for exempt in self.security_middleware.https.redirect_exempt_paths:
            if path.startswith(exempt):
                return True
        return False

    def is_path_suspicious(self, path: str) -> bool:
        """
        Check if a path matches suspicious patterns.

        Args:
            path: Request path

        Returns:
            True if suspicious, False otherwise
        """
        if not self.security_middleware.request_validation.block_suspicious_paths:
            return False
        for pattern in self.security_middleware.request_validation.suspicious_patterns:
            if pattern in path:
                return True
        return False


# =============================================================================
# CONVENIENCE FUNCTIONS
# =============================================================================


def get_middleware_config() -> MiddlewareConfig:
    """
    Load and return middleware configuration.

    This is the primary entry point for accessing middleware configuration.

    Example:
        from lightwave.schema.pydantic.contracts.middleware import get_middleware_config

        config = get_middleware_config()
        stack = config.get_middleware_paths("production")
    """
    return MiddlewareConfig.load()
