import logging
from datetime import datetime
from typing import List, Dict

logger = logging.getLogger(__name__)

class DisclosureEngine:
    def __init__(self, template_path: str = None):
        self.template_path = template_path

    def suggest_remediation(self, vuln_type: str) -> str:
        """Return specific code fix suggestion based on vulnerability type."""
        suggestions = {
            'xss': "Sanitize all user inputs with DOMPurify on the client-side and use output encoding (e.g., escapeHTML) on the server. Implement Content Security Policy (CSP).",
            'sqli': "Use parameterized queries/prepared statements. For MongoDB, use $escape or mongoose's built-in sanitization. Validate and sanitize input.",
            'idor': "Implement Role-Based Access Control (RBAC) and ensure that every request checks the user's ownership of the resource. Use indirect object references (maps).",
            'injection': "Validate input against a whitelist. Use safe APIs and avoid dynamic evaluation (eval, exec).",
        }
        return suggestions.get(vuln_type.lower(), "Apply secure coding practices and input validation.")

    def generate_report(self, findings: List[Dict], target: str) -> str:
        """Create a Markdown vulnerability disclosure report."""
        now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')
        report = f"""# Vulnerability Disclosure Report

**Target:** {target}  
**Date:** {now}  
**Report ID:** OMNICLAW-{now[:10].replace('-','')}  

## Summary
{len(findings)} confirmed vulnerabilities were identified during automated assessment.

## Detailed Findings

"""
        for idx, f in enumerate(findings, 1):
            vuln_type = f['payload'].get('type', 'unknown')
            remediation = self.suggest_remediation(vuln_type)
            report += f"""
### {idx}. {vuln_type.upper()} at {f['payload']['endpoint']}

- **Method:** {f['payload']['method']}
- **Payload:** `{f['payload']['payload_data']}`
- **Evidence Hash:** `{f['hash']}`
- **Source Code Leaked:** {f['leaked_source']}
- **Response Status:** {f['status']}

**Remediation:**  
{remediation}

**Chain of Custody:**  
Evidence hash recorded and stored securely.

---
"""
        report += "\n*Report generated by OmniClaw Autonomous Vulnerability Validation Framework.*"
        return report

    def save_report(self, report: str, filename: str = "disclosure_report.md"):
        with open(filename, 'w') as f:
            f.write(report)
        logger.info(f"Report saved to {filename}")
