"""
Pydantic schemas for Infrastructure Django model JSONFields.

These schemas validate data stored in PostgreSQL JSONB columns
for infrastructure security audit models.
"""

from typing import Literal

from pydantic import Field

from lightwave.schema.pydantic.core.base import JSONFieldSchema

# =============================================================================
# SECURITY AUDIT REPORT SCHEMAS
# =============================================================================


class AttackResultSchema(JSONFieldSchema):
    """
    Schema for individual attack test result.

    Example:
        {
            "attack_type": "sql_injection",
            "target": "/api/users",
            "payload": "' OR 1=1 --",
            "status": "blocked",
            "response_code": 403,
            "detection_time_ms": 12
        }
    """

    attack_type: str = Field(..., description="Type of attack tested")
    target: str = Field(..., description="Target endpoint or resource")
    payload: str = Field("", description="Attack payload used (sanitized)")
    status: Literal["blocked", "detected", "passed", "failed"] = Field(..., description="Result of the attack test")
    response_code: int | None = Field(None, description="HTTP response code")
    detection_time_ms: float | None = Field(None, description="Time to detect/block in milliseconds")
    details: str = Field("", description="Additional details about the result")


class VulnerabilityScanResultSchema(JSONFieldSchema):
    """
    Schema for vulnerability scan results.

    Example:
        {
            "scanner": "trivy",
            "target": "docker-image:latest",
            "vulnerabilities": [
                {"id": "CVE-2023-1234", "severity": "HIGH", "package": "openssl"}
            ],
            "scan_time": "2024-01-15T10:30:00Z"
        }
    """

    scanner: str = Field(..., description="Scanner tool used")
    target: str = Field(..., description="What was scanned")
    vulnerabilities: list[dict] = Field(default_factory=list, description="Found vulnerabilities")
    scan_time: str = Field("", description="When the scan was performed (ISO format)")


class SecurityDrillReportSchema(JSONFieldSchema):
    """
    Schema for full security drill report data.

    This is the schema for SecurityAuditLog.report_data JSONField.

    Example:
        {
            "drill_version": "1.0",
            "environment": "production",
            "attack_results": [...],
            "vulnerability_scan": {...},
            "recommendations": ["Enable WAF", "Update dependencies"],
            "summary": "3 of 10 attack vectors blocked"
        }
    """

    drill_version: str = Field("1.0", description="Version of the drill framework")
    environment: str = Field(..., description="Environment tested (production, staging)")
    attack_results: list[AttackResultSchema] = Field(default_factory=list, description="Results of attack simulations")
    vulnerability_scan: VulnerabilityScanResultSchema | None = Field(
        None, description="Vulnerability scan results if performed"
    )
    recommendations: list[str] = Field(default_factory=list, description="Security recommendations based on findings")
    summary: str = Field("", description="Executive summary of drill results")
    started_at: str = Field("", description="Drill start time (ISO format)")
    completed_at: str = Field("", description="Drill completion time (ISO format)")


# =============================================================================
# VALIDATION HELPERS
# =============================================================================


def validate_report_data(data: dict) -> SecurityDrillReportSchema:
    """Validate report_data JSONField."""
    return SecurityDrillReportSchema(**data)
