#!/usr/bin/env python3
"""
Test script for compliance templates.

Tests GDPR, HIPAA, SOC2, ISO27001, and PCI DSS compliance templates
to ensure they provide appropriate behavioral contract configurations.
"""

from behavioural_contracts.compliance_templates import ComplianceTemplates, create_compliant_agent


def test_gdpr_template():
    """Test GDPR compliance template."""
    print("\n🇪🇺 TESTING GDPR COMPLIANCE TEMPLATE")
    print("=" * 50)

    template = ComplianceTemplates.gdpr_template()

    # Check key GDPR requirements
    assert template["compliance_framework"] == "GDPR"
    assert template["policy"]["pii"] is False
    assert template["policy"]["data_subject_rights"]["right_to_erasure"]
    assert template["policy"]["consent_required"]
    assert template["policy"]["data_minimization"]
    assert "GDPR" in template["policy"]["compliance_tags"]

    # Check strict temperature control for compliance
    assert template["behavioural_flags"]["temperature_control"]["range"][1] <= 0.3

    # Check required fields include compliance status
    assert "compliance_status" in template["response_contract"]["output_format"]["required_fields"]
    assert "privacy_impact" in template["response_contract"]["output_format"]["required_fields"]

    print("✅ GDPR template validation passed")
    print(f"Temperature range: {template['behavioural_flags']['temperature_control']['range']}")
    print(f"Compliance tags: {template['policy']['compliance_tags']}")


def test_hipaa_template():
    """Test HIPAA compliance template."""
    print("\n🏥 TESTING HIPAA COMPLIANCE TEMPLATE")
    print("=" * 50)

    template = ComplianceTemplates.hipaa_template()

    # Check key HIPAA requirements
    assert template["compliance_framework"] == "HIPAA"
    assert template["policy"]["phi_protection"]
    assert template["policy"]["minimum_necessary"]
    assert template["policy"]["access_controls"]["encryption_required"]
    assert "HIPAA" in template["policy"]["compliance_tags"]
    assert "PHI-PROTECTED" in template["policy"]["compliance_tags"]

    # Check extremely conservative temperature for healthcare
    assert template["behavioural_flags"]["temperature_control"]["range"][1] <= 0.2

    # Check PHI-specific fields
    assert (
        "hipaa_compliance_status"
        in template["response_contract"]["output_format"]["required_fields"]
    )
    assert (
        "phi_risk_assessment" in template["response_contract"]["output_format"]["required_fields"]
    )

    # Check breach notification requirements
    assert template["breach_notification"]["notification_required"]
    assert template["breach_notification"]["notification_timeline"] == "60_days"

    print("✅ HIPAA template validation passed")
    print(f"Temperature range: {template['behavioural_flags']['temperature_control']['range']}")
    print(
        f"Breach notification timeline: {template['breach_notification']['notification_timeline']}"
    )


def test_soc2_template():
    """Test SOC 2 compliance template."""
    print("\n🏢 TESTING SOC 2 COMPLIANCE TEMPLATE")
    print("=" * 50)

    template = ComplianceTemplates.soc2_template()

    # Check key SOC 2 requirements
    assert template["compliance_framework"] == "SOC2"
    assert template["policy"]["security_controls"]["access_controls"]
    assert template["policy"]["availability_controls"]["system_monitoring"]
    assert template["policy"]["processing_integrity"]["data_validation"]
    assert template["policy"]["confidentiality"]["encryption_controls"]
    assert "SOC2" in template["policy"]["compliance_tags"]

    # Check all trust criteria fields are required
    trust_criteria_fields = [
        "security_assessment",
        "availability_status",
        "processing_integrity",
        "confidentiality_level",
        "privacy_compliance",
    ]
    for field in trust_criteria_fields:
        assert field in template["response_contract"]["output_format"]["required_fields"]

    # Check monitoring requirements
    assert template["monitoring"]["continuous_monitoring"]
    assert template["monitoring"]["real_time_alerts"]

    print("✅ SOC 2 template validation passed")
    print(f"Trust criteria fields: {trust_criteria_fields}")
    print(f"Monitoring enabled: {template['monitoring']['continuous_monitoring']}")


def test_multi_compliance():
    """Test multi-framework compliance template."""
    print("\n🔒 TESTING MULTI-COMPLIANCE TEMPLATE")
    print("=" * 50)

    # Create a template that satisfies both GDPR and HIPAA
    frameworks = ["gdpr", "hipaa"]
    template = ComplianceTemplates.create_multi_compliance_template(frameworks)

    # Should have combined compliance tags
    assert "GDPR" in template["policy"]["compliance_tags"]
    assert "HIPAA" in template["policy"]["compliance_tags"]
    assert "PHI-PROTECTED" in template["policy"]["compliance_tags"]

    # Should have fields from both frameworks
    required_fields = template["response_contract"]["output_format"]["required_fields"]
    assert "compliance_status" in required_fields  # From GDPR
    assert "hipaa_compliance_status" in required_fields  # From HIPAA
    assert "privacy_impact" in required_fields  # From GDPR
    assert "phi_risk_assessment" in required_fields  # From HIPAA

    # Should use strictest temperature control (HIPAA is stricter)
    assert template["behavioural_flags"]["temperature_control"]["range"][1] <= 0.2

    print("✅ Multi-compliance template validation passed")
    print(f"Combined frameworks: {template['compliance_frameworks']}")
    print(f"Compliance tags: {template['policy']['compliance_tags']}")
    print(f"Temperature range: {template['behavioural_flags']['temperature_control']['range']}")


def test_compliant_agent_decorator():
    """Test the compliant agent decorator."""
    print("\n🤖 TESTING COMPLIANT AGENT DECORATOR")
    print("=" * 50)

    @create_compliant_agent("gdpr")
    def gdpr_data_processor(data: str, purpose: str) -> dict:
        """GDPR-compliant data processing agent."""
        return {
            "compliance_status": "compliant",
            "data_processing_basis": "legitimate_interest",
            "privacy_impact": "low",
            "recommendations": ["Data processed according to GDPR requirements"],
            "processed_data": f"Processed: {data} for purpose: {purpose}",
        }

    # Test normal operation
    try:
        result = gdpr_data_processor("user analytics data", "service improvement")
        print("✅ GDPR agent executed successfully")
        print(f"Compliance status: {result.get('compliance_status', 'unknown')}")
        print(f"Privacy impact: {result.get('privacy_impact', 'unknown')}")
    except Exception as e:
        print(f"❌ GDPR agent failed: {e}")

    # Test with PII (should be blocked)
    @create_compliant_agent("hipaa")
    def hipaa_health_analyzer(health_data: str) -> dict:
        """HIPAA-compliant health data analyzer."""
        return {
            "hipaa_compliance_status": "compliant",
            "phi_risk_assessment": "low",
            "safeguards_applied": ["encryption", "access_control"],
            "recommendations": ["PHI handled according to HIPAA requirements"],
            "covered_entity_notification": "not_required",
        }

    try:
        result = hipaa_health_analyzer("Patient symptoms and medical history")
        print("✅ HIPAA agent executed successfully")
        print(f"PHI risk assessment: {result.get('phi_risk_assessment', 'unknown')}")
    except Exception as e:
        print(f"❌ HIPAA agent failed: {e}")


def test_framework_listing():
    """Test framework listing and template retrieval."""
    print("\n📋 TESTING FRAMEWORK LISTING")
    print("=" * 50)

    frameworks = ComplianceTemplates.list_frameworks()
    print(f"Available frameworks: {frameworks}")

    # Test each framework can be retrieved
    for framework in frameworks:
        try:
            template = ComplianceTemplates.get_template(framework)
            assert template["compliance_framework"].upper() == framework.upper()
            print(f"✅ {framework.upper()} template retrieved successfully")
        except Exception as e:
            print(f"❌ {framework.upper()} template failed: {e}")

    # Test invalid framework
    try:
        ComplianceTemplates.get_template("invalid_framework")
        print("❌ Should have failed for invalid framework")
    except ValueError as e:
        print(f"✅ Correctly rejected invalid framework: {e}")


def test_compliance_validation():
    """Test that compliance templates have required structure."""
    print("\n✅ TESTING COMPLIANCE TEMPLATE VALIDATION")
    print("=" * 50)

    frameworks = ComplianceTemplates.list_frameworks()

    for framework in frameworks:
        template = ComplianceTemplates.get_template(framework)

        # Check required top-level fields
        required_fields = [
            "version",
            "description",
            "compliance_framework",
            "policy",
            "behavioural_flags",
            "response_contract",
        ]

        for field in required_fields:
            assert field in template, f"{framework} missing required field: {field}"

        # Check policy has compliance_tags
        assert "compliance_tags" in template["policy"], f"{framework} missing compliance_tags"
        assert len(template["policy"]["compliance_tags"]) > 0, (
            f"{framework} has empty compliance_tags"
        )

        # Check behavioral flags have temperature control
        assert "temperature_control" in template["behavioural_flags"], (
            f"{framework} missing temperature_control"
        )
        temp_control = template["behavioural_flags"]["temperature_control"]
        assert "mode" in temp_control and "range" in temp_control, (
            f"{framework} invalid temperature_control"
        )

        # Check response contract has required fields
        assert "output_format" in template["response_contract"], (
            f"{framework} missing output_format"
        )
        assert "required_fields" in template["response_contract"]["output_format"], (
            f"{framework} missing required_fields"
        )

        print(f"✅ {framework.upper()} template structure validated")


def main():
    """Run all compliance template tests."""
    print("🚀 COMPLIANCE TEMPLATES TEST SUITE")
    print("=" * 80)
    print("Testing GDPR, HIPAA, SOC2, ISO27001, and PCI DSS compliance templates")

    # Run all tests
    test_gdpr_template()
    test_hipaa_template()
    test_soc2_template()
    test_multi_compliance()
    test_compliant_agent_decorator()
    test_framework_listing()
    test_compliance_validation()

    print("\n" + "=" * 80)
    print("🎉 COMPLIANCE TEMPLATES TESTING COMPLETE")
    print("The compliance framework now includes:")
    print("✅ GDPR (EU) - General Data Protection Regulation")
    print("✅ HIPAA (US) - Health Insurance Portability and Accountability Act")
    print("✅ SOC 2 - Service Organization Control 2")
    print("✅ ISO 27001 - Information Security Management")
    print("✅ PCI DSS - Payment Card Industry Data Security Standard")
    print("✅ Multi-framework compliance support")
    print("✅ Automated compliance validation and enforcement")


if __name__ == "__main__":
    main()
