import os
from datetime import datetime
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

# Import from package namespace
from agent_ops_cockpit.ops import arch_review, reliability, secret_scanner, ui_auditor
from agent_ops_cockpit.eval import quality_climber, red_team
from agent_ops_cockpit import optimizer

console = Console()

class CockpitOrchestrator:
    """
    Main orchestrator for AgentOps audits.
    Runs Arch Review, Quality Baseline, Red Team, and Performance tests.
    """
    
    def __init__(self):
        self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.report_path = "cockpit_final_report.md"
        self.results = {}

    def run_step(self, name: str, func, *args, **kwargs):
        console.print(f"\n🚀 [bold]Step: {name}[/bold]")
        try:
            # Capturing output for internal functions is harder without redirecting stdout
            # For now, we just execute them for the effect and note success
            func(*args, **kwargs)
            self.results[name] = {
                "success": True,
                "output": f"Audit {name} executed successfully."
            }
            console.print(f"✅ {name} Completed.")
        except Exception as e:
            self.results[name] = {"success": False, "output": str(e)}
            console.print(f"❌ {name} Failed: {e}")

    def generate_report(self):
        report = [
            "# 🏁 AgentOps Cockpit: Final Audit Report",
            f"**Timestamp**: {self.timestamp}",
            f"**Status**: {'PASS' if all(r['success'] for r in self.results.values()) else 'FAIL'}",
            "\n---",
            "\n## 📊 Executive Summary"
        ]
        
        summary_table = Table(show_header=True, header_style="bold magenta")
        summary_table.add_column("Audit Type")
        summary_table.add_column("Status")
        
        for name, data in self.results.items():
            status = "✅ PASS" if data["success"] else "❌ FAIL"
            summary_table.add_row(name, status)
            report.append(f"- **{name}**: {status}")

        console.print("\n", summary_table)
        
        report.append("\n## 🔍 Detailed Findings")
        for name, data in self.results.items():
            report.append(f"\n### {name}")
            report.append(data["output"])

        report.append("\n---")
        report.append("\n*Generated by the AgentOps Cockpit Orchestrator.*")
        
        with open(self.report_path, "w") as f:
            f.write("\n".join(report))
        
        console.print(f"\n✨ [bold green]Final Report generated at {self.report_path}[/bold green]")

def run_full_audit():
    orchestrator = CockpitOrchestrator()
    
    console.print(Panel.fit(
        "🕹️ [bold blue]AGENTOPS COCKPIT: FULL SYSTEM AUDIT[/bold blue]\nLaunching all governance and optimization modules...",
        border_style="blue"
    ))

    # 1. Architecture Review
    orchestrator.run_step("Architecture Review", arch_review.audit, path=".")
    
    # 2. Quality Baseline
    orchestrator.run_step("Quality Baseline", quality_climber.audit, path=".")
    
    # 3. Security & Secrets
    orchestrator.run_step("Secret Scanner (Leak Detection)", secret_scanner.scan, path=".")
    orchestrator.run_step("Adversarial Security (Red Team)", red_team.audit, agent_path="src/backend/agent.py")
    
    # 4. Face (UI/UX) Audit
    orchestrator.run_step("UI/UX Quality (Face Auditor)", ui_auditor.audit, path="src")
    
    # 5. Token Optimization Audit
    orchestrator.run_step("Token Optimization Audit", optimizer.audit, file_path="src/backend/agent.py", interactive=False)

    # 6. Reliability Audit (Unit + Regression)
    orchestrator.run_step("Reliability (Unit + Regression)", reliability.run_tests)

    orchestrator.generate_report()

if __name__ == "__main__":
    run_full_audit()
