"""License management commands."""

import typer
from rich.console import Console
from rich.table import Table

from apiposture_pro.licensing.manager import ProLicenseManager

app = typer.Typer(help="License management commands")
console = Console()


@app.command("activate")
def activate(license_key: str) -> None:
    """
    Activate Pro license.

    Args:
        license_key: Your Pro license key
    """
    manager = ProLicenseManager()

    try:
        console.print("[dim]Activating license...[/dim]")
        context = manager.activate(license_key)

        console.print("[green]✓[/green] License activated successfully!")
        console.print(f"\n[bold]Customer:[/bold] {context.customer_name}")
        console.print(f"[bold]Email:[/bold] {context.customer_email}")
        console.print(f"[bold]Tier:[/bold] {context.tier}")
        console.print(f"[bold]Expires:[/bold] {context.expires_at.strftime('%Y-%m-%d')}")

    except Exception as e:
        console.print(f"[red]✗[/red] Activation failed: {e}")
        raise typer.Exit(1) from e


@app.command("deactivate")
def deactivate() -> None:
    """Deactivate current license."""
    manager = ProLicenseManager()

    if not manager.is_valid():
        console.print("[yellow]![/yellow] No active license to deactivate")
        raise typer.Exit(1)

    manager.deactivate()
    console.print("[green]✓[/green] License deactivated successfully")


@app.command("status")
def status() -> None:
    """Show current license status."""
    manager = ProLicenseManager()

    if not manager.is_valid():
        console.print("[red]✗[/red] No active license")
        console.print("\nActivate with: apiposture-pro activate <license-key>")
        raise typer.Exit(1)

    context = manager.get_context()
    if not context:
        console.print("[red]✗[/red] License context not available")
        raise typer.Exit(1)

    # Create status table
    table = Table(title="License Status", show_header=True)
    table.add_column("Property", style="cyan")
    table.add_column("Value", style="white")

    table.add_row("Status", "[green]Active[/green]")
    table.add_row("Customer", context.customer_name)
    table.add_row("Email", context.customer_email)
    table.add_row("Tier", context.tier.upper())
    table.add_row("Expires", context.expires_at.strftime("%Y-%m-%d %H:%M:%S UTC"))

    if context.features:
        table.add_row("Features", ", ".join(context.features))

    if context.machine_id:
        table.add_row("Machine ID", context.machine_id[:16] + "...")

    console.print(table)
