import click
import json
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich.panel import Panel
from civicshield_core.analyzer.engine import run_scan
from civicshield_core.analyzer.phishing_detector import PhishingDetector

console = Console()

@click.group()
def cli():
    """CivicShield Engine CLI"""
    pass

@click.command()
@click.option("--url", required=True, help="Target URL to scan")
def scan(url):
    console.print(Panel(f"[bold cyan]CivicShield AI Scanner[/bold cyan]\nTarget: [green]{url}[/green]"))
    
    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
        TimeElapsedColumn(),
        console=console,
    ) as progress:
        task = progress.add_task("[cyan]Initializing...", total=100)
        
        def update_progress(stage, percent, message, stats):
            progress.update(task, completed=percent, description=f"[cyan]{message}")
        
        report = run_scan(url, progress_callback=update_progress)

    console.print(f"\n[bold green]Scan Complete![/bold green] Found [bold red]{len(report['findings'])}[/bold red] vulnerabilities.", style="bold")
    
    severity = report.get('summary', {}).get('severity_counts', {})
    table = Table(title="Risk Severity Summary")
    table.add_column("Severity", style="cyan", no_wrap=True)
    table.add_column("Count", style="magenta")
    
    for sev, count in severity.items():
        color = "red" if sev == "critical" else "yellow" if sev == "high" else "blue" if sev == "medium" else "green"
        table.add_row(f"[{color}]{sev.upper()}[/{color}]", str(count))
        
    console.print(table)

@click.command()
@click.option("--url", required=True, help="Target URL to check for phishing")
def phish(url):
    console.print(f"[bold cyan]Checking[/bold cyan] [green]{url}[/green] [bold cyan]for phishing indicators...[/bold cyan]")
    detector = PhishingDetector()
    result = detector.analyze(url)
    console.print(Panel(f"[bold]Threat Score:[/bold] {result.get('threat_score', 0)}\n[bold]Confidence:[/bold] {result.get('confidence', 0)}\n[bold]Is Phishing:[/bold] {'[red]Yes[/red]' if result.get('is_phishing') else '[green]No[/green]'}", title="Phishing Analysis Result", expand=False))

cli.add_command(scan)
cli.add_command(phish)

if __name__ == "__main__":
    cli()
