"""
CHRONOS CLI Main Entry Point
============================

Main command-line interface for the CHRONOS quantum security platform.
Provides commands for threat detection, security analysis, and defense operations.
"""

import sys
from typing import Optional
from pathlib import Path

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

from chronos import __version__
from chronos.cli.commands import detect, analyze, defend, config, readiness, pqc, vault
from chronos.cli.utils import error_handler, ChronosCLIError

# Initialize Rich console for formatted output
console = Console()

# ASCII Art Banner
BANNER = """
 ██████╗██╗  ██╗██████╗  ██████╗ ███╗   ██╗ ██████╗ ███████╗
██╔════╝██║  ██║██╔══██╗██╔═══██╗████╗  ██║██╔═══██╗██╔════╝
██║     ███████║██████╔╝██║   ██║██╔██╗ ██║██║   ██║███████╗
██║     ██╔══██║██╔══██╗██║   ██║██║╚██╗██║██║   ██║╚════██║
╚██████╗██║  ██║██║  ██║╚██████╔╝██║ ╚████║╚██████╔╝███████║
 ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝ ╚══════╝
"""

# Custom help text
HELP_TEXT = """
[bold blue]CHRONOS[/bold blue] - [italic]Unified Quantum Security Platform[/italic]

Protecting systems against present and future quantum threats.

[bold yellow]Commands:[/bold yellow]
  [green]detect[/green]   Scan and detect security threats
  [green]analyze[/green]  Analyze cryptographic vulnerabilities  
  [green]defend[/green]   Activate defensive countermeasures

[bold yellow]Examples:[/bold yellow]
  chronos detect --target ./myproject
  chronos analyze --crypto-audit
  chronos defend --quantum-shield

[dim]For more info on a command: chronos <command> --help[/dim]
"""


def version_callback(value: bool) -> None:
    """Display version information and exit."""
    if value:
        console.print(Panel(
            f"[bold blue]CHRONOS[/bold blue] Quantum Security Platform\n"
            f"Version: [green]{__version__}[/green]\n"
            f"Python: [cyan]{sys.version.split()[0]}[/cyan]",
            title="Version Info",
            border_style="blue"
        ))
        raise typer.Exit()


def banner_callback(value: bool) -> None:
    """Display ASCII banner and exit."""
    if value:
        console.print(f"[bold blue]{BANNER}[/bold blue]")
        console.print(f"[dim]Version {__version__} - Quantum Security Platform[/dim]\n")
        raise typer.Exit()


# Main Application
app = typer.Typer(
    name="chronos",
    help="CHRONOS - Unified Quantum Security Platform for present and future threats.",
    add_completion=True,
    rich_markup_mode="rich",
    no_args_is_help=True,
    context_settings={"help_option_names": ["-h", "--help"]},
)

# Register sub-command groups
app.add_typer(detect.app, name="detect", help="🔍 Scan and detect security threats")
app.add_typer(analyze.app, name="analyze", help="📊 Analyze cryptographic vulnerabilities")
app.add_typer(defend.app, name="defend", help="🛡️ Activate defensive countermeasures")
app.add_typer(config.app, name="config", help="⚙️ Configuration management")
app.add_typer(readiness.app, name="readiness", help="📈 Quantum readiness assessment")
app.add_typer(pqc.app, name="pqc", help="🔐 Post-quantum cryptography migration")
app.add_typer(vault.app, name="vault", help="🔒 Quantum-secure data vault operations")


@app.callback(invoke_without_command=True)
def main_callback(
    ctx: typer.Context,
    version: bool = typer.Option(
        False,
        "--version",
        "-v",
        help="Show version information and exit.",
        callback=version_callback,
        is_eager=True,
    ),
    banner: bool = typer.Option(
        False,
        "--banner",
        "-b",
        help="Display CHRONOS banner.",
        callback=banner_callback,
        is_eager=True,
    ),
    verbose: bool = typer.Option(
        False,
        "--verbose",
        "-V",
        help="Enable verbose output.",
    ),
) -> None:
    """
    [bold blue]CHRONOS[/bold blue] - Unified Quantum Security Platform
    
    Protecting systems against present and future quantum threats.
    """
    # Store verbose flag in context for sub-commands
    ctx.ensure_object(dict)
    ctx.obj["verbose"] = verbose
    
    if ctx.invoked_subcommand is None:
        # No subcommand provided, show custom help
        console.print(Panel(
            HELP_TEXT,
            title="[bold blue]CHRONOS[/bold blue]",
            subtitle=f"v{__version__}",
            border_style="blue",
        ))


@app.command("status")
def status_command(
    detailed: bool = typer.Option(False, "--detailed", "-d", help="Show detailed status"),
) -> None:
    """
    📋 Check the status of CHRONOS services and components.
    """
    with error_handler(console):
        table = Table(title="CHRONOS System Status", border_style="blue")
        table.add_column("Component", style="cyan")
        table.add_column("Status", style="green")
        table.add_column("Details", style="dim")
        
        # Core components status
        components = [
            ("Core Engine", "✓ Online", "v0.1.0"),
            ("Threat Detector", "✓ Ready", "0 active scans"),
            ("Crypto Analyzer", "✓ Ready", "Post-quantum enabled"),
            ("Defense Shield", "○ Standby", "Awaiting activation"),
            ("Quantum Module", "✓ Ready", "Lattice-based crypto loaded"),
        ]
        
        for component, status, details in components:
            table.add_row(component, status, details if detailed else "")
        
        console.print(table)
        console.print("\n[bold green]✓[/bold green] CHRONOS is operational\n")


@app.command("init")
def init_command(
    path: Path = typer.Argument(
        Path("."),
        help="Path to initialize CHRONOS configuration",
        exists=False,
    ),
    force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing config"),
) -> None:
    """
    🚀 Initialize CHRONOS configuration in a project.
    """
    with error_handler(console):
        config_path = path / ".chronos"
        
        if config_path.exists() and not force:
            console.print(
                f"[yellow]⚠[/yellow] Configuration already exists at {config_path}\n"
                f"Use [bold]--force[/bold] to overwrite."
            )
            raise typer.Exit(1)
        
        # Create configuration directory
        config_path.mkdir(parents=True, exist_ok=True)
        
        # Create default config file
        config_file = config_path / "config.yaml"
        config_file.write_text(
            "# CHRONOS Configuration\n"
            "version: 0.1.0\n"
            "security_level: high\n"
            "quantum_resistant: true\n"
            "modules:\n"
            "  detect: enabled\n"
            "  analyze: enabled\n"
            "  defend: enabled\n"
        )
        
        console.print(Panel(
            f"[green]✓[/green] CHRONOS initialized at [cyan]{path.absolute()}[/cyan]\n\n"
            f"Configuration: [dim]{config_file}[/dim]\n\n"
            f"[yellow]Next steps:[/yellow]\n"
            f"  1. Run [bold]chronos status[/bold] to verify installation\n"
            f"  2. Run [bold]chronos detect scan[/bold] to scan for threats\n"
            f"  3. Run [bold]chronos analyze crypto[/bold] to audit cryptography",
            title="Initialization Complete",
            border_style="green",
        ))


def main() -> None:
    """Main entry point for the CLI."""
    try:
        app()
    except KeyboardInterrupt:
        console.print("\n[yellow]Operation cancelled by user.[/yellow]")
        sys.exit(130)
    except Exception as e:
        console.print(f"\n[bold red]Error:[/bold red] {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
