"""
Simulation Analysis & Reporting Tool

Generates summary reports and visualizations from simulation logs.
"""

import json
import statistics
from pathlib import Path
from datetime import datetime

class SimulationReporter:
    """
    Analyzes simulation data and generates markdown/JSON reports.
    """

    def __init__(self, output_dir: str = "reports"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)

    def generate_summary(self, tester_stats: dict, fault_history: list, ledger_len: int):
        """Generate a markdown report of the simulation"""
        report_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_path = self.output_dir / f"sim_report_{report_id}.md"

        # Calculate fault statistics
        total_faults = len(fault_history)
        fault_types = {}
        recovery_times = []
        for f in fault_history:
            ftype = f.get("detector", "UNKNOWN")
            fault_types[ftype] = fault_types.get(ftype, 0) + 1

            # Check for recovery time in metadata/details
            details = f.get("details", {})
            if "recovery_duration" in details:
                recovery_times.append(details["recovery_duration"])

        # Calculate success ratio
        submitted = tester_stats.get("submitted_total", 0)
        failed = tester_stats.get("failed_total", 0)
        success_ratio = ((submitted - failed) / submitted * 100) if submitted > 0 else 0

        # MTTR
        mttr = statistics.mean(recovery_times) if recovery_times else 0

        md_content = f"""# ALTRUS Simulation Performance Report
Report Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}

## 📊 High-Level Metrics
- **Success Ratio**: {success_ratio:.2f}%
- **Total Intents Submitted**: {submitted}
- **Intents Failed**: {failed}
- **Avg Submission Latency**: {tester_stats.get('avg_submission_latency_ms', 0):.2f} ms
- **Total Faults Detected**: {total_faults}
- **Mean Time to Recovery (MTTR)**: {mttr:.4f}s
- **Ledger Depth**: {ledger_len} blocks

## 💉 Fault Injection Summary
| Fault Type | Count |
|------------|-------|
"""
        for ftype, count in fault_types.items():
            md_content += f"| {ftype} | {count} |\n"

        if recovery_times:
            md_content += "\n## ⏱️ Recovery Analysis\n"
            md_content += "```mermaid\ngraph LR\n"
            for i, rtime in enumerate(recovery_times[:10]):
                md_content += f"  F{i}[Fault {i}] -->|{rtime:.2f}s| R{i}[Recovered]\n"
            md_content += "```\n"

        md_content += """
## 🏁 Conclusion
"""
        if success_ratio > 95:
            md_content += "System demonstrated **HIGH STABILITY** under load."
        elif success_ratio > 80:
            md_content += "System demonstrated **MODERATE STABILITY**. Observe latency spikes."
        else:
            md_content += "System demonstrated **LOW STABILITY**. Immediate performance tuning required."

        with report_path.open("w") as f:
            f.write(md_content)

        print(f"📊 Report generated at {report_path}")
        return report_path

    def export_raw_json(self, data: dict):
        """Export raw simulation data to JSON"""
        report_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        json_path = self.output_dir / f"sim_data_{report_id}.json"

        with json_path.open("w") as f:
            json.dump(data, f, indent=2)

        return json_path
