"""
GitLab security scanning configurations and compliance frameworks
"""

import json
from typing import Dict, Any, List


def get_gitlab_security_compliance() -> str:
    """
    GitLab security scanning configurations, compliance frameworks, and audit requirements
    
    Returns:
        JSON string with GitLab security and compliance configurations
    """
    security_data = {
        "title": "GitLab Security & Compliance Framework",
        "description": "Comprehensive security scanning and compliance configurations for GitLab CI/CD",
        "storm_logger_integration": {
            "security_logging": [
                "Structured security event logging",
                "Compliance audit trail generation",
                "Security metrics collection and reporting",
                "Automated compliance dashboard updates"
            ]
        },
        "security_scanning": {
            "sast": {
                "description": "Static Application Security Testing",
                "gitlab_config": {
                    "include": [
                        {"template": "Security/SAST.gitlab-ci.yml"}
                    ],
                    "variables": {
                        "SAST_CONFIDENCE_LEVEL": "3",
                        "SAST_EXCLUDED_PATHS": "spec, test, tests, tmp",
                        "STORM_LOGGER_LEVEL": "INFO"
                    },
                    "sast": {
                        "stage": "security",
                        "script": [
                            "echo 'Running SAST with Storm Logger integration...'",
                            "# Storm Logger: Track security scan start",
                            "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-sast'); logger.track_business_event('sast_scan_start', {'confidence_level': 3})\""
                        ],
                        "after_script": [
                            "# Storm Logger: Track security scan completion",
                            "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-sast'); logger.track_business_event('sast_scan_complete', {'findings': 'extracted_from_report'})\""
                        ]
                    }
                },
                "supported_languages": [
                    "Python", "Java", "JavaScript", "C#", "Go", "Ruby", "PHP", "Scala"
                ],
                "compliance_mapping": {
                    "soc2": "CC6.1 - Logical access controls",
                    "pci_dss": "PCI DSS 6.5 - Secure coding practices",
                    "iso27001": "A.14.2.1 - Secure development policy"
                }
            },
            "dependency_scanning": {
                "description": "Third-party dependency vulnerability scanning",
                "gitlab_config": {
                    "include": [
                        {"template": "Security/Dependency-Scanning.gitlab-ci.yml"}
                    ],
                    "variables": {
                        "DS_EXCLUDED_PATHS": "spec, test, tests, tmp"
                    },
                    "dependency_scanning": {
                        "stage": "security",
                        "script": [
                            "echo 'Running dependency scanning...'",
                            "# Storm Logger: Track dependency scan",
                            "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-deps'); logger.info('Dependency scan started')\""
                        ]
                    }
                },
                "supported_package_managers": [
                    "npm", "pip", "maven", "gradle", "bundler", "composer", "go modules"
                ]
            },
            "secret_detection": {
                "description": "Exposed secrets and credentials detection",
                "gitlab_config": {
                    "include": [
                        {"template": "Security/Secret-Detection.gitlab-ci.yml"}
                    ],
                    "secret_detection": {
                        "stage": "security",
                        "script": [
                            "echo 'Running secret detection...'",
                            "# Storm Logger: Track secret detection",
                            "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-secrets'); logger.info('Secret detection started')\""
                        ]
                    }
                }
            },
            "container_scanning": {
                "description": "Container image vulnerability scanning",
                "gitlab_config": {
                    "include": [
                        {"template": "Security/Container-Scanning.gitlab-ci.yml"}
                    ],
                    "container_scanning": {
                        "stage": "security",
                        "script": [
                            "echo 'Running container scanning...'",
                            "# Storm Logger: Track container scan",
                            "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-containers'); logger.info('Container scan started')\""
                        ]
                    }
                }
            }
        },
        "compliance_frameworks": {
            "soc2": {
                "description": "SOC 2 Type II compliance for security and availability",
                "requirements": [
                    "Access controls and authentication",
                    "System monitoring and logging",
                    "Data encryption and protection",
                    "Incident response procedures"
                ],
                "gitlab_controls": [
                    "User access management",
                    "Pipeline security scanning",
                    "Audit logging with Storm Logger",
                    "Automated compliance reporting"
                ],
                "storm_logger_features": [
                    "Comprehensive audit trails",
                    "Security event tracking",
                    "Compliance dashboard integration",
                    "Automated report generation"
                ]
            },
            "pci_dss": {
                "description": "PCI DSS compliance for payment card industry",
                "requirements": [
                    "Secure network and systems",
                    "Protect cardholder data",
                    "Maintain vulnerability management",
                    "Implement access controls"
                ],
                "gitlab_controls": [
                    "Network segmentation",
                    "Data encryption in transit/rest",
                    "Regular security testing",
                    "Access monitoring and logging"
                ],
                "storm_logger_features": [
                    "PCI-compliant logging",
                    "Cardholder data sanitization",
                    "Access control monitoring",
                    "Security metrics tracking"
                ]
            },
            "iso27001": {
                "description": "ISO 27001 information security management",
                "requirements": [
                    "Information security policy",
                    "Risk assessment and treatment",
                    "Security awareness and training",
                    "Incident management"
                ],
                "gitlab_controls": [
                    "Security policy enforcement",
                    "Risk-based testing",
                    "Security training tracking",
                    "Incident response automation"
                ],
                "storm_logger_features": [
                    "Policy compliance monitoring",
                    "Risk assessment logging",
                    "Security training metrics",
                    "Incident tracking and reporting"
                ]
            }
        },
        "security_best_practices": {
            "pipeline_security": [
                "Use protected branches and merge requests",
                "Implement approval workflows",
                "Enable security scanning on all branches",
                "Monitor and alert on security findings"
            ],
            "secret_management": [
                "Use GitLab CI/CD variables for secrets",
                "Implement secret rotation policies",
                "Monitor for exposed secrets",
                "Use vault integration for sensitive data"
            ],
            "access_control": [
                "Implement role-based access control",
                "Use multi-factor authentication",
                "Monitor user access and activities",
                "Regular access reviews and audits"
            ],
            "monitoring_and_logging": [
                "Comprehensive security event logging",
                "Real-time security monitoring",
                "Automated threat detection",
                "Incident response automation"
            ]
        }
    }
    
    return json.dumps(security_data, indent=2)


def get_security_templates() -> Dict[str, Any]:
    """
    Get security scanning templates
    
    Returns:
        Dictionary with security scanning templates
    """
    return {
        "comprehensive_security": {
            "include": [
                {"template": "Security/SAST.gitlab-ci.yml"},
                {"template": "Security/Dependency-Scanning.gitlab-ci.yml"},
                {"template": "Security/Secret-Detection.gitlab-ci.yml"},
                {"template": "Security/Container-Scanning.gitlab-ci.yml"}
            ],
            "variables": {
                "SAST_CONFIDENCE_LEVEL": "3",
                "SAST_EXCLUDED_PATHS": "spec, test, tests, tmp",
                "STORM_LOGGER_LEVEL": "INFO",
                "STORM_ENABLE_SECURITY_METRICS": "true"
            }
        },
        "python_security": {
            "security_scanning": {
                "stage": "security",
                "script": [
                    "echo 'Running Python security scanning...'",
                    "pip install bandit safety",
                    "bandit -r . -f json -o bandit-report.json",
                    "safety check --json --output safety-report.json",
                    "python -c \"from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-security'); logger.track_business_event('security_scan', {'tools': ['bandit', 'safety']})\""
                ],
                "artifacts": {
                    "reports": {
                        "sast": "bandit-report.json"
                    }
                }
            }
        }
    }


def get_compliance_checklists() -> Dict[str, Any]:
    """
    Get compliance checklists for different frameworks
    
    Returns:
        Dictionary with compliance checklists
    """
    return {
        "soc2_checklist": {
            "access_controls": [
                "Implement multi-factor authentication",
                "Use role-based access control",
                "Monitor user access and activities",
                "Regular access reviews and audits"
            ],
            "monitoring": [
                "Comprehensive logging with Storm Logger",
                "Real-time monitoring and alerting",
                "Security event tracking",
                "Automated compliance reporting"
            ],
            "data_protection": [
                "Encrypt data in transit and at rest",
                "Implement data classification",
                "Monitor data access and usage",
                "Regular backup and recovery testing"
            ]
        },
        "pci_dss_checklist": {
            "network_security": [
                "Network segmentation",
                "Firewall configuration",
                "Secure network protocols",
                "Regular network testing"
            ],
            "data_protection": [
                "Cardholder data encryption",
                "Data sanitization in logs",
                "Secure data transmission",
                "Data retention policies"
            ],
            "vulnerability_management": [
                "Regular security scanning",
                "Vulnerability assessment",
                "Patch management",
                "Security testing"
            ]
        },
        "iso27001_checklist": {
            "information_security_policy": [
                "Security policy documentation",
                "Policy implementation",
                "Regular policy review",
                "Policy compliance monitoring"
            ],
            "risk_management": [
                "Risk assessment procedures",
                "Risk treatment plans",
                "Risk monitoring",
                "Regular risk reviews"
            ],
            "incident_management": [
                "Incident response procedures",
                "Incident tracking and reporting",
                "Incident analysis and lessons learned",
                "Incident response testing"
            ]
        }
    }


def get_security_metrics() -> Dict[str, Any]:
    """
    Get security metrics and KPIs
    
    Returns:
        Dictionary with security metrics
    """
    return {
        "vulnerability_metrics": {
            "sast_findings": "Number of static analysis findings",
            "dependency_vulnerabilities": "Number of dependency vulnerabilities",
            "secret_detections": "Number of exposed secrets detected",
            "container_vulnerabilities": "Number of container vulnerabilities"
        },
        "compliance_metrics": {
            "policy_compliance": "Percentage of policies compliant",
            "control_effectiveness": "Percentage of controls effective",
            "audit_findings": "Number of audit findings",
            "remediation_time": "Average time to remediate findings"
        },
        "operational_metrics": {
            "security_scan_frequency": "Frequency of security scans",
            "scan_success_rate": "Percentage of successful scans",
            "false_positive_rate": "Percentage of false positives",
            "mean_time_to_remediation": "Average time to fix vulnerabilities"
        }
    }