"""Main CLI application for ApiPosturePro."""

import os
import sys

import typer
from rich.console import Console

from apiposture_pro import __version__
from apiposture_pro.cli import diff as diff_commands
from apiposture_pro.cli import history as history_commands
from apiposture_pro.cli import license as license_commands
from apiposture_pro.cli import scan as scan_commands
from apiposture_pro.deployment.deployer import ExtensionDeployer
from apiposture_pro.licensing.manager import ProLicenseManager

app = typer.Typer(
    name="apiposture-pro",
    help="Professional security analysis for Python REST APIs",
    add_completion=False,
)

# Add license subcommands
app.add_typer(license_commands.app, name="license", hidden=True)
app.command("activate")(license_commands.activate)
app.command("deactivate")(license_commands.deactivate)
app.command("status")(license_commands.status)

# Add scan command
app.command("scan")(scan_commands.scan)

# Add diff command
app.command("diff")(diff_commands.diff)

# Add history subcommands
app.add_typer(history_commands.app, name="history")

console = Console()


def version_callback(value: bool) -> None:
    """Show version information."""
    if value:
        console.print(f"ApiPosturePro version {__version__}")
        raise typer.Exit()


@app.callback()
def main(
    version: bool | None = typer.Option(
        None,
        "--version",
        "-v",
        callback=version_callback,
        is_eager=True,
        help="Show version information",
    ),
) -> None:
    """
    ApiPosturePro - Professional security analysis for Python REST APIs.

    Requires a valid license key. Activate with:
        apiposture-pro activate <license-key>

    Or set environment variable:
        export APIPOSTURE_LICENSE_KEY=<your-key>
    """
    # Auto-deploy as extension if license key is in environment
    license_key = os.getenv("APIPOSTURE_LICENSE_KEY")
    if license_key:
        try:
            deployer = ExtensionDeployer()
            if not deployer.is_deployed():
                console.print("[dim]Auto-deploying Pro extension...[/dim]")
                deployer.deploy()
        except Exception:
            # Silent failure for auto-deploy, don't block CLI usage
            pass


@app.command()
def hello() -> None:
    """Test command to verify CLI is working."""
    console.print(f"[bold green]ApiPosturePro v{__version__} is working![/bold green]")
    console.print("\nAvailable commands:")
    console.print("  • scan      - Scan a Python project for security issues")
    console.print("  • diff      - Compare two scan results (Phase 5 ✓)")
    console.print("  • history   - View scan history (Phase 6 ✓)")
    console.print("  • activate  - Activate Pro license")
    console.print("  • status    - Show license status")

    # Check license status
    manager = ProLicenseManager()
    if manager.is_valid():
        context = manager.get_context()
        if context:
            console.print(f"\n[green]✓[/green] License active: {context.tier}")
    else:
        console.print("\n[yellow]![/yellow] No active license. Run: apiposture-pro activate <key>")


def cli_main() -> None:
    """Entry point for CLI."""
    try:
        app()
    except KeyboardInterrupt:
        console.print("\n[yellow]Interrupted by user[/yellow]")
        sys.exit(130)
    except Exception as e:
        console.print(f"[red]Error:[/red] {e}")
        sys.exit(1)


if __name__ == "__main__":
    cli_main()
