"""
Compliance templates for GDPR, HIPAA, and SOC2.

This module provides pre-configured behavioral contract templates
for major compliance frameworks to ensure agents meet regulatory
requirements automatically.
"""

from typing import Any


class ComplianceTemplates:
    """Pre-configured compliance templates for regulatory frameworks."""

    @staticmethod
    def gdpr_template() -> dict[str, Any]:
        """
        GDPR (General Data Protection Regulation) compliance template.

        Ensures agent compliance with EU data protection requirements:
        - Data minimization
        - Purpose limitation
        - Storage limitation
        - Lawful basis for processing
        - Data subject rights
        """
        return {
            "version": "1.0.0",
            "description": "GDPR-compliant behavioral contract",
            "compliance_framework": "GDPR",
            "policy": {
                "pii": False,  # No PII processing unless explicitly allowed
                "data_retention": {
                    "max_retention_days": 365,  # Default 1 year retention
                    "automatic_deletion": True,
                    "retention_policy": "minimal",
                },
                "lawful_basis": "legitimate_interest",  # Default basis
                "data_subject_rights": {
                    "right_to_access": True,
                    "right_to_rectification": True,
                    "right_to_erasure": True,
                    "right_to_portability": True,
                    "right_to_object": True,
                },
                "consent_required": True,
                "purpose_limitation": True,
                "data_minimization": True,
                "compliance_tags": ["GDPR", "EU-DATA-PROTECTION"],
            },
            "behavioural_flags": {
                "conservatism": "high",
                "data_handling": "strict",
                "privacy_protection": "maximum",
                "temperature_control": {
                    "mode": "strict",
                    "range": [0.1, 0.3],  # Very conservative for compliance
                },
            },
            "response_contract": {
                "output_format": {
                    "required_fields": [
                        "compliance_status",
                        "data_processing_basis",
                        "privacy_impact",
                        "recommendations",
                    ]
                },
                "safety_checks": {
                    "pii_protection": True,
                    "data_minimization": True,
                    "purpose_validation": True,
                    "consent_verification": True,
                },
                "privacy_controls": {
                    "pseudonymization": True,
                    "encryption_required": True,
                    "access_logging": True,
                    "data_classification": True,
                },
            },
            "escalation": {
                "on_privacy_violation": "immediate_escalation",
                "on_consent_missing": "block_processing",
                "on_retention_exceeded": "automatic_deletion",
                "on_cross_border_transfer": "adequacy_check",
            },
            "audit": {
                "logging_required": True,
                "audit_trail": True,
                "compliance_reporting": True,
                "dpo_notification": True,
            },
        }

    @staticmethod
    def hipaa_template() -> dict[str, Any]:
        """
        HIPAA (Health Insurance Portability and Accountability Act) compliance template.

        Ensures agent compliance with US healthcare data protection:
        - PHI (Protected Health Information) safeguards
        - Administrative safeguards
        - Physical safeguards
        - Technical safeguards
        - Breach notification requirements
        """
        return {
            "version": "1.0.0",
            "description": "HIPAA-compliant behavioral contract",
            "compliance_framework": "HIPAA",
            "policy": {
                "phi_protection": True,
                "minimum_necessary": True,  # Use minimum necessary standard
                "purpose_limitation": "healthcare_operations",
                "access_controls": {
                    "role_based_access": True,
                    "unique_user_identification": True,
                    "automatic_logoff": True,
                    "encryption_required": True,
                },
                "audit_controls": {
                    "audit_logging": True,
                    "access_monitoring": True,
                    "review_required": True,
                },
                "integrity_controls": {
                    "data_integrity": True,
                    "transmission_security": True,
                    "authentication": True,
                },
                "compliance_tags": ["HIPAA", "PHI-PROTECTED", "HEALTHCARE"],
            },
            "behavioural_flags": {
                "conservatism": "maximum",
                "healthcare_mode": True,
                "phi_handling": "strict",
                "temperature_control": {
                    "mode": "strict",
                    "range": [0.05, 0.2],  # Extremely conservative for healthcare
                },
            },
            "response_contract": {
                "output_format": {
                    "required_fields": [
                        "hipaa_compliance_status",
                        "phi_risk_assessment",
                        "safeguards_applied",
                        "recommendations",
                        "covered_entity_notification",
                    ]
                },
                "safety_checks": {
                    "phi_detection": True,
                    "de_identification": True,
                    "minimum_necessary_check": True,
                    "authorization_verification": True,
                },
                "technical_safeguards": {
                    "access_control": True,
                    "audit_controls": True,
                    "integrity": True,
                    "transmission_security": True,
                },
                "administrative_safeguards": {
                    "security_officer_designated": True,
                    "workforce_training": True,
                    "access_management": True,
                    "incident_procedures": True,
                },
            },
            "escalation": {
                "on_phi_breach": "immediate_notification",
                "on_unauthorized_access": "security_incident",
                "on_integrity_violation": "data_validation",
                "on_transmission_failure": "secure_retry",
            },
            "breach_notification": {
                "notification_required": True,
                "notification_timeline": "60_days",
                "hhs_notification": True,
                "individual_notification": True,
                "media_notification_threshold": 500,
            },
        }

    @staticmethod
    def soc2_template() -> dict[str, Any]:
        """
        SOC 2 (Service Organization Control 2) compliance template.

        Ensures agent compliance with SOC 2 trust criteria:
        - Security
        - Availability
        - Processing Integrity
        - Confidentiality
        - Privacy
        """
        return {
            "version": "1.0.0",
            "description": "SOC 2-compliant behavioral contract",
            "compliance_framework": "SOC2",
            "policy": {
                "security_controls": {
                    "access_controls": True,
                    "logical_security": True,
                    "network_security": True,
                    "vulnerability_management": True,
                },
                "availability_controls": {
                    "system_monitoring": True,
                    "backup_procedures": True,
                    "disaster_recovery": True,
                    "capacity_planning": True,
                },
                "processing_integrity": {
                    "data_validation": True,
                    "error_handling": True,
                    "processing_controls": True,
                    "output_validation": True,
                },
                "confidentiality": {
                    "data_classification": True,
                    "encryption_controls": True,
                    "secure_disposal": True,
                    "confidentiality_agreements": True,
                },
                "privacy_controls": {
                    "notice_and_communication": True,
                    "choice_and_consent": True,
                    "collection_limitation": True,
                    "quality_maintenance": True,
                },
                "compliance_tags": ["SOC2", "TRUST-SERVICES", "SECURITY"],
            },
            "behavioural_flags": {
                "conservatism": "high",
                "security_focus": True,
                "availability_priority": "high",
                "temperature_control": {
                    "mode": "strict",
                    "range": [0.1, 0.4],  # Conservative for enterprise compliance
                },
            },
            "response_contract": {
                "output_format": {
                    "required_fields": [
                        "security_assessment",
                        "availability_status",
                        "processing_integrity",
                        "confidentiality_level",
                        "privacy_compliance",
                        "recommendations",
                    ]
                },
                "safety_checks": {
                    "security_validation": True,
                    "availability_check": True,
                    "integrity_verification": True,
                    "confidentiality_protection": True,
                    "privacy_assessment": True,
                },
                "control_objectives": {
                    "common_criteria": {
                        "control_environment": True,
                        "communication": True,
                        "risk_assessment": True,
                        "monitoring_activities": True,
                    },
                    "security_criteria": {
                        "access_controls": True,
                        "logical_security": True,
                        "network_security": True,
                    },
                },
            },
            "monitoring": {
                "continuous_monitoring": True,
                "real_time_alerts": True,
                "performance_metrics": True,
                "compliance_reporting": True,
            },
            "escalation": {
                "on_security_incident": "immediate_response",
                "on_availability_issue": "service_restoration",
                "on_integrity_failure": "data_validation",
                "on_confidentiality_breach": "containment_procedures",
            },
        }

    @staticmethod
    def iso27001_template() -> dict[str, Any]:
        """
        ISO 27001 Information Security Management System compliance template.
        """
        return {
            "version": "1.0.0",
            "description": "ISO 27001-compliant behavioral contract",
            "compliance_framework": "ISO27001",
            "policy": {
                "information_security": {
                    "confidentiality": True,
                    "integrity": True,
                    "availability": True,
                },
                "risk_management": {
                    "risk_assessment": True,
                    "risk_treatment": True,
                    "risk_monitoring": True,
                },
                "access_control": {
                    "user_access_management": True,
                    "privileged_access_rights": True,
                    "information_access_restriction": True,
                },
                "compliance_tags": ["ISO27001", "ISMS", "INFORMATION-SECURITY"],
            },
            "behavioural_flags": {
                "conservatism": "high",
                "information_security": "strict",
                "temperature_control": {"mode": "strict", "range": [0.1, 0.3]},
            },
            "response_contract": {
                "output_format": {
                    "required_fields": [
                        "security_controls",
                        "risk_assessment",
                        "compliance_status",
                        "recommendations",
                    ]
                },
                "safety_checks": {
                    "information_classification": True,
                    "access_authorization": True,
                    "security_incident_detection": True,
                },
            },
        }

    @staticmethod
    def pci_dss_template() -> dict[str, Any]:
        """
        PCI DSS (Payment Card Industry Data Security Standard) compliance template.
        """
        return {
            "version": "1.0.0",
            "description": "PCI DSS-compliant behavioral contract",
            "compliance_framework": "PCI_DSS",
            "policy": {
                "cardholder_data_protection": {
                    "data_encryption": True,
                    "secure_transmission": True,
                    "access_restriction": True,
                    "secure_deletion": True,
                },
                "network_security": {
                    "firewall_configuration": True,
                    "network_segmentation": True,
                    "secure_protocols": True,
                },
                "compliance_tags": ["PCI-DSS", "PAYMENT-CARD", "FINANCIAL"],
            },
            "behavioural_flags": {
                "conservatism": "maximum",
                "payment_security": "strict",
                "temperature_control": {"mode": "strict", "range": [0.05, 0.2]},
            },
            "response_contract": {
                "output_format": {
                    "required_fields": [
                        "pci_compliance_status",
                        "cardholder_data_risk",
                        "security_controls",
                        "recommendations",
                    ]
                },
                "safety_checks": {
                    "cardholder_data_detection": True,
                    "encryption_validation": True,
                    "access_logging": True,
                },
            },
        }

    @staticmethod
    def get_template(framework: str) -> dict[str, Any]:
        """
        Get a compliance template by framework name.

        Args:
            framework: Compliance framework name (gdpr, hipaa, soc2, iso27001, pci_dss)

        Returns:
            Compliance template dictionary

        Raises:
            ValueError: If framework is not supported
        """
        templates = {
            "gdpr": ComplianceTemplates.gdpr_template,
            "hipaa": ComplianceTemplates.hipaa_template,
            "soc2": ComplianceTemplates.soc2_template,
            "iso27001": ComplianceTemplates.iso27001_template,
            "pci_dss": ComplianceTemplates.pci_dss_template,
        }

        if framework.lower() not in templates:
            raise ValueError(
                f"Unsupported compliance framework: {framework}. "
                f"Supported frameworks: {list(templates.keys())}"
            )

        return templates[framework.lower()]()

    @staticmethod
    def list_frameworks() -> list[str]:
        """List all available compliance frameworks."""
        return ["gdpr", "hipaa", "soc2", "iso27001", "pci_dss"]

    @staticmethod
    def create_multi_compliance_template(frameworks: list[str]) -> dict[str, Any]:
        """
        Create a behavioral contract that satisfies multiple compliance frameworks.

        Args:
            frameworks: List of framework names to combine

        Returns:
            Combined compliance template with strictest requirements
        """
        if not frameworks:
            raise ValueError("At least one framework must be specified")

        # Start with the first framework
        combined = ComplianceTemplates.get_template(frameworks[0])
        combined["description"] = f"Multi-compliance behavioral contract: {', '.join(frameworks)}"
        combined["compliance_frameworks"] = frameworks

        # Combine requirements from all frameworks
        for framework in frameworks[1:]:
            template = ComplianceTemplates.get_template(framework)

            # Merge compliance tags
            combined["policy"]["compliance_tags"].extend(
                template["policy"].get("compliance_tags", [])
            )

            # Take strictest temperature control
            if (
                template["behavioural_flags"]["temperature_control"]["range"][1]
                < combined["behavioural_flags"]["temperature_control"]["range"][1]
            ):
                combined["behavioural_flags"]["temperature_control"] = template[
                    "behavioural_flags"
                ]["temperature_control"]

            # Merge required fields
            combined["response_contract"]["output_format"]["required_fields"].extend(
                template["response_contract"]["output_format"].get("required_fields", [])
            )

            # Enable all safety checks
            combined_safety = combined["response_contract"]["safety_checks"]
            template_safety = template["response_contract"]["safety_checks"]
            for check, enabled in template_safety.items():
                if enabled:
                    combined_safety[check] = True

        # Remove duplicates from compliance tags and required fields
        combined["policy"]["compliance_tags"] = list(set(combined["policy"]["compliance_tags"]))
        combined["response_contract"]["output_format"]["required_fields"] = list(
            set(combined["response_contract"]["output_format"]["required_fields"])
        )

        return combined


def create_compliant_agent(framework: str):
    """
    Decorator factory for creating compliance-aware agents.

    Args:
        framework: Compliance framework name

    Returns:
        Decorator function
    """
    from .contract import behavioural_contract

    template = ComplianceTemplates.get_template(framework)
    return behavioural_contract(template)
