import sys
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from pyshield.exporters import BaseExporter

class TerminalExporter(BaseExporter):
    def export(self):
        console = Console()
        
        # We can write to a file via rich if an output is given, but terminal format is typically for stdout.
        # cli_plan.yaml asks for terminal layout to be colorized.
        
        score = self.report["scoring"]["vibe_to_value_score"]
        risk_level = self.report["scoring"]["risk_level"]
        counts = self.report["findings_overview"]
        
        title = Text("PyShield Security Report", style="bold white on blue", justify="center")
        console.print(Panel(title, border_style="blue"))
        
        # Scoring Section
        score_color = "red" if score < 70 else "green"
        risk_color = "red" if risk_level in ["High", "Critical"] else "yellow" if risk_level == "Medium" else "green"
        
        console.print(f"\n[bold]Score:[/bold] [{score_color}]{score:.2f}/100[/{score_color}]")
        console.print(f"[bold]Risk Level:[/bold] [{risk_color}]{risk_level}[/{risk_color}]\n")
        
        # Severity Section
        console.print("[bold underline]Severity Breakdown[/bold underline]")
        console.print(f"[red]Critical:[/red] {counts['critical_count']}")
        console.print(f"[yellow]High:[/yellow]     {counts['high_count']}")
        console.print(f"[blue]Medium:[/blue]   {counts['medium_count']}")
        console.print(f"[white]Low:[/white]      {counts['low_count']}\n")
        
        # Top Findings limit to 5 as per cli_plan.yaml
        console.print("[bold underline]Top Findings[/bold underline]")
        issues = self.report["detailed_findings"]["issues"]
        if not issues:
            console.print("No issues found! Excellent.", style="bold green")
        else:
            limit = 5
            for i, issue in enumerate(issues[:limit]):
                sev = issue["severity"]
                color = "red" if sev in ["CRITICAL", "HIGH"] else "blue" if sev == "MEDIUM" else "white"
                console.print(f"- [[{color}]{sev}[/{color}]] {issue['issue_type']} ({issue['file']}:{issue['line']})")
            
            if len(issues) > limit:
                console.print(f"...and {len(issues) - limit} more issues.", style="dim")
                
        console.print("\n[dim]---------------------------------------[/dim]")
        console.print("[dim]Scan completed successfully.[/dim]")
