"""Menu interativo estilo ferramenta OSINT — navegação por setas, sem
precisar decorar flags de comando."""

import questionary
from questionary import Style
from rich.console import Console

from abyss.ui.banner import section, show_banner

console = Console()

# Paleta terminal verde/preto, no mesmo espírito do Cerberus/ÆGIS
HACKER_STYLE = Style([
    ("qmark", "fg:#00ff41 bold"),
    ("question", "fg:#e0e0e0 bold"),
    ("answer", "fg:#00ff41 bold"),
    ("pointer", "fg:#00ff41 bold"),
    ("highlighted", "fg:#00ff41 bold"),
    ("selected", "fg:#00ff41"),
    ("separator", "fg:#666666"),
    ("instruction", "fg:#888888"),
    ("text", "fg:#e0e0e0"),
])


def prompt_repo_path(default: str = "") -> str:
    raw = questionary.path(
        "Caminho do repositório alvo (Enter = diretório atual):",
        default=default,
        style=HACKER_STYLE,
    ).ask()
    return raw.strip() if raw and raw.strip() else "."


def main_menu() -> str:
    show_banner()
    choice = questionary.select(
        "Selecione uma operação:",
        choices=[
            questionary.Choice("[1] Scan completo (secrets + dependências)", value="full"),
            questionary.Choice("[2] Scan de secrets vazados", value="secrets"),
            questionary.Choice("[3] Scan de dependências vulneráveis", value="deps"),
            questionary.Choice("[4] Instalar/atualizar gitleaks", value="install_gitleaks"),
            questionary.Choice("[0] Sair", value="exit"),
        ],
        style=HACKER_STYLE,
        qmark=">",
        instruction=" ",
    ).ask()
    return choice or "exit"


def prompt_export_json() -> bool:
    return questionary.confirm(
        "Exportar relatório em JSON?",
        default=False,
        style=HACKER_STYLE,
    ).ask()


def run_interactive():
    from pathlib import Path

    from abyss.cli import _print_dependency_findings, _print_secret_findings, _write_json
    from abyss.scanners import dependencies, secrets

    while True:
        choice = main_menu()

        if choice == "exit":
            console.print("\n[dim green]encerrando sessão...[/dim green]\n")
            break

        if choice == "install_gitleaks":
            from abyss.core.installer import install, is_installed

            section("INSTALAÇÃO — GITLEAKS")
            if is_installed():
                console.print("[green]✓[/green] gitleaks já está instalado.")
            else:
                install(progress_callback=lambda msg: console.print(f"[dim]{msg}[/dim]"))
                console.print("[green]✓[/green] gitleaks instalado com sucesso.")
            questionary.press_any_key_to_continue(style=HACKER_STYLE).ask()
            continue

        repo_path = prompt_repo_path()
        if not repo_path:
            continue

        resolved = str(Path(repo_path).resolve())
        if not Path(resolved).exists():
            console.print(f"[red]✗ caminho não encontrado:[/red] {resolved}")
            questionary.press_any_key_to_continue(style=HACKER_STYLE).ask()
            continue

        secret_findings, dep_findings = [], []

        if choice in ("full", "secrets"):
            section("SCANNING — SECRETS")
            with console.status("[green]procurando secrets vazados...[/green]"):
                secret_findings = secrets.scan_repo(resolved, progress_callback=console.print)
            _print_secret_findings(secret_findings)

        if choice in ("full", "deps"):
            section("SCANNING — DEPENDENCIES")
            with console.status("[green]auditando dependências...[/green]"):
                dep_findings = dependencies.scan_repo(resolved)
            _print_dependency_findings(dep_findings)

        total = len(secret_findings) + len(dep_findings)
        section("RESULTADO")
        if total == 0:
            console.print("[bold green]✓ nenhum problema encontrado.[/bold green]")
        else:
            console.print(f"[bold yellow]⚠ {total} problema(s) encontrado(s).[/bold yellow]")

            if prompt_export_json():
                output_path = questionary.path(
                    "Salvar relatório em:", default="abyss-report.json", style=HACKER_STYLE
                ).ask()
                if output_path:
                    _write_json(Path(output_path), secret_findings, dep_findings, resolved)
                    console.print(f"[dim]relatório salvo em {output_path}[/dim]")

        questionary.press_any_key_to_continue(style=HACKER_STYLE).ask()