"""Scan command for Pro version."""

import time
from pathlib import Path
from typing import Annotated

import typer
from rich.console import Console

from apiposture_pro.analysis.pro_analyzer import ProAnalyzer
from apiposture_pro.features.historical_tracking.store import HistoryStore
from apiposture_pro.licensing.manager import ProLicenseManager

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


@app.command("scan")
def scan(
    path: Annotated[
        Path,
        typer.Argument(
            help="Path to Python project to scan",
            exists=True,
            file_okay=False,
            dir_okay=True,
        ),
    ] = Path("."),
    output: Annotated[
        str,
        typer.Option(
            "--output",
            "-o",
            help="Output format (text, json, sarif)",
        ),
    ] = "text",
    output_file: Annotated[
        Path | None,
        typer.Option(
            "--file",
            "-f",
            help="Output file path",
        ),
    ] = None,
    with_history: Annotated[
        bool,
        typer.Option(
            "--with-history",
            help="Save scan to history database",
        ),
    ] = False,
    show_risk_score: Annotated[
        bool,
        typer.Option(
            "--risk-score/--no-risk-score",
            help="Show risk score calculation",
        ),
    ] = True,
) -> None:
    """
    Scan a Python project for security issues.

    Requires valid Pro license.
    """
    # Validate license
    license_manager = ProLicenseManager()
    if not license_manager.is_valid():
        console.print("[red]✗[/red] No valid license found")
        console.print("\nActivate your license with: apiposture-pro activate <key>")
        console.print("Or set environment variable: APIPOSTURE_LICENSE_KEY")
        raise typer.Exit(1)

    context = license_manager.get_context()
    if not context:
        console.print("[red]✗[/red] Could not retrieve license context")
        raise typer.Exit(1)

    # Show license info
    console.print(
        f"[dim]Scanning with {context.tier.upper()} license ({context.customer_name})[/dim]\n"
    )

    # Create analyzer
    analyzer = ProAnalyzer()

    # Run scan
    try:
        console.print(f"[cyan]Scanning:[/cyan] {path.absolute()}")
        console.print("[dim]Loading Pro rules...[/dim]")

        start_time = time.time()
        result = analyzer.analyze(path)
        duration_ms = int((time.time() - start_time) * 1000)

        # Display results
        console.print("\n[bold]Scan Complete[/bold]")
        console.print(f"  Endpoints found: {len(result.endpoints)}")
        console.print(f"  Findings: {len(result.findings)}")

        # Show findings summary by severity
        from collections import Counter

        severity_counts = Counter(f.severity for f in result.findings)
        if severity_counts:
            console.print("\n[bold]Findings by Severity:[/bold]")
            for severity in ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]:
                count = severity_counts.get(severity, 0)
                if count > 0:
                    color = {
                        "CRITICAL": "red",
                        "HIGH": "red",
                        "MEDIUM": "yellow",
                        "LOW": "blue",
                        "INFO": "dim",
                    }.get(severity, "white")
                    console.print(f"  [{color}]{severity}[/{color}]: {count}")

        # Show risk score
        if show_risk_score and hasattr(result, "risk_details"):
            risk = result.risk_details
            console.print("\n[bold]Risk Score:[/bold]")
            console.print(
                f"  [{risk.color}]{risk.total_score}/100 ({risk.risk_level.value})[/{risk.color}]"
            )
            console.print(f"  Findings: {risk.findings_score}/50")
            console.print(f"  Exposure: {risk.exposure_score}/30")
            console.print(f"  Surface Area: {risk.surface_area_score}/20")

        # Save to history if requested
        if with_history:
            console.print("\n[dim]Saving to history database...[/dim]")
            try:
                store = HistoryStore()
                scan_id = store.save_scan(
                    result, duration_ms=duration_ms, risk_score=getattr(result, "risk_score", 0)
                )
                console.print(f"[green]✓[/green] Saved as scan #{scan_id}")
            except Exception as e:
                console.print(f"[yellow]![/yellow] Failed to save to history: {e}")

        # Export results if requested
        if output_file:
            console.print(f"\n[dim]Writing results to {output_file}...[/dim]")
            # TODO: Implement output formatting
            console.print("[yellow]![/yellow] File export not yet implemented")

        # Exit with code 1 if critical or high findings
        critical_high_count = (
            severity_counts.get("CRITICAL", 0) + severity_counts.get("HIGH", 0)
        )
        if critical_high_count > 0:
            console.print(
                f"\n[yellow]![/yellow] Found {critical_high_count} critical/high severity issues"
            )
            raise typer.Exit(1)

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