"""Verify command — integrity checksum validation for scan records."""

from __future__ import annotations

from pathlib import Path
from typing import Annotated

import typer
from rich.console import Console

from apiposture_pro.licensing.manager import ProLicenseManager
from apiposture_pro.licensing.models import LicenseErrorCode, LicenseValidationResult

app = typer.Typer(help="Verify command")
console = Console()


def verify(
    scan_id: Annotated[
        int | None,
        typer.Option(
            "--scan-id",
            help="Scan ID to verify (defaults to latest scan for current directory)",
        ),
    ] = None,
) -> None:
    """
    Verify the integrity of a scan record by recomputing its checksum.

    Exit 0 = integrity confirmed. Exit 1 = tampered or not found.

    Requires enterprise license tier.
    """
    license_manager = ProLicenseManager()
    validation = license_manager.validate()
    if not validation.is_valid:
        _print_license_error(validation)
        raise typer.Exit(1)

    context = validation.context
    if not context or not context.is_enterprise_or_higher:
        console.print("[red]✗[/red] 'verify' requires an enterprise license tier.")
        raise typer.Exit(1)

    try:
        from apiposture_pro.enterprise.audit_trail.checksum import compute_scan_checksum
        from apiposture_pro.features.historical_tracking.store import HistoryStore

        store = HistoryStore()

        if scan_id is not None:
            record = store.get_scan(scan_id)
        else:
            # Default: latest scan for current directory
            scans = store.list_scans(
                project_path=str(Path(".").absolute()), limit=1
            )
            record = scans[0] if scans else None

        if record is None:
            console.print("[red]✗[/red] No scan record found to verify.")
            raise typer.Exit(1)

        if not record.checksum:
            console.print(
                f"[yellow]![/yellow] Scan #{record.id} has no stored checksum — cannot verify."
            )
            raise typer.Exit(1)

        recomputed = compute_scan_checksum(
            scan_id=str(record.id),
            timestamp=record.scan_time.isoformat() if record.scan_time else "",
            scanned_path=record.project_path,
            findings_json=record.findings_json or "",
        )

        if recomputed == record.checksum:
            console.print(
                f"[green]✓[/green] Scan #{record.id} integrity confirmed "
                f"(checksum: {record.checksum[:16]}…)"
            )
            raise typer.Exit(0)
        else:
            console.print(
                f"[red]✗[/red] Scan #{record.id} TAMPERED — "
                f"stored: {record.checksum[:16]}… "
                f"recomputed: {recomputed[:16]}…"
            )
            raise typer.Exit(1)

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


def _print_license_error(result: LicenseValidationResult) -> None:
    """Print error-code-specific license error message."""
    messages = {
        LicenseErrorCode.EXPIRED: f"[red]✗[/red] Your license has expired. {result.error_message}",
        LicenseErrorCode.MACHINE_MISMATCH: "[red]✗[/red] License is bound to a different machine.",
        LicenseErrorCode.REVOKED: "[red]✗[/red] Your license has been revoked.",
        LicenseErrorCode.INVALID_SIGNATURE: "[red]✗[/red] License key has an invalid signature.",
    }
    msg = messages.get(
        result.error_code,
        f"[red]✗[/red] No valid license found. {result.error_message}",
    )
    console.print(msg)
    console.print("\nActivate your license with: apiposture-pro activate <key>")
