#!/usr/bin/env python3
"""
health_dashboard.py — Sovereign Health & Observability Dashboard.

Aggregates data from Muda, Guardrails, Token Optimizer, and Quality Gates
into a single, unified health report for the Timmy Foundation fleet.
"""

import os
import sys
import json
import subprocess
from datetime import datetime
from pathlib import Path

REPORTS_DIR = Path("reports")
DASHBOARD_FILE = Path("SOVEREIGN_HEALTH.md")

class HealthDashboard:
    def __init__(self):
        REPORTS_DIR.mkdir(exist_ok=True)

    def run_tool(self, name: str, cmd: str) -> str:
        print(f"[*] Running {name}...")
        try:
            # Capture output
            res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            return res.stdout
        except Exception as e:
            return f"Error running {name}: {e}"

    def generate_report(self):
        print("--- Generating Sovereign Health Dashboard ---")
        
        # 1. Run Audits
        muda_output = self.run_tool("Muda Audit", "python3 scripts/muda_audit.py")
        guardrails_output = self.run_tool("Agent Guardrails", "python3 scripts/agent_guardrails.py")
        optimizer_output = self.run_tool("Token Optimizer", "python3 scripts/token_optimizer.py")
        gate_output = self.run_tool("Quality Gate", "python3 scripts/ci_automation_gate.py .")

        # 2. Build Markdown
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        md = [
            f"# 🛡️ Sovereign Health Dashboard",
            f"**Last Updated:** {now}",
            f"",
            f"## 📊 Summary",
            f"- **Fleet Status:** ACTIVE",
            f"- **Security Posture:** MONITORING",
            f"- **Operational Waste:** AUDITED",
            f"",
            f"## ♻️ Muda Waste Audit",
            f"```\n{muda_output}\n```",
            f"",
            f"## 🕵️ Agent Guardrails",
            f"```\n{guardrails_output}\n```",
            f"",
            f"## 🪙 Token Efficiency",
            f"```\n{optimizer_output}\n```",
            f"",
            f"## 🏗️ CI Quality Gate",
            f"```\n{gate_output}\n```",
            f"",
            f"---",
            f"*Generated by Sovereign Infrastructure Suite*"
        ]

        with open(DASHBOARD_FILE, "w") as f:
            f.write("\n".join(md))
        
        print(f"[SUCCESS] Dashboard generated at {DASHBOARD_FILE}")

if __name__ == "__main__":
    dashboard = HealthDashboard()
    dashboard.generate_report()
