# src/ctf/cli_analyse.py
# {{{ imports
import click
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from ctf.analysis import run_analysis
# }}}

# {{{ analyse_cmd
@click.command(name="analyse")
@click.option('-f', '--file', type=click.Path(exists=True), help="Path to the challenge file to analyze.")
def analyse_cmd(file):
    """Dynamically analyze and try to solve the active challenge using static routes."""
    console = Console()
    console.print("[bold blue][*] Starting dynamic challenge analysis...[/bold blue]\n")
    
    file_path = Path(file) if file else None
    result = run_analysis(file_path)
    
    for route in result.routes:
        title = f"Route: {route.route_name}"
        if not route.executed:
            console.print(Panel(
                f"[yellow]{route.message}[/yellow]",
                title=title,
                border_style="yellow"
            ))
        elif route.success:
            content = f"[green]{route.message}[/green]\n"
            if route.details:
                content += "\n[bold cyan]Details:[/bold cyan]\n"
                for k, v in route.details.items():
                    content += f"  • {k}: {v}\n"
            if route.extracted_flags:
                content += "\n[bold green]✓ Extracted Flags:[/bold green]\n"
                for flag in route.extracted_flags:
                    content += f"  [bold green]{flag}[/bold green]\n"
            console.print(Panel(
                content.strip(),
                title=title,
                border_style="green"
            ))
        else:
            console.print(Panel(
                f"[red]✗ {route.message}[/red]",
                title=title,
                border_style="red"
            ))
            
    if result.success:
        console.print("\n[bold green]✓ Analysis complete. Challenge solved successfully![/bold green]")
    else:
        console.print("\n[bold yellow]! Analysis complete. No clear flag found yet.[/bold yellow]")
# }}}
