import click
import tomli_w
from pydantic import FilePath
from rich.console import Console

from vulnsearch.cli.render import print_cpe_table, print_vulns_table
from vulnsearch.consolidation import consolidate_vulnerabilities
from vulnsearch.models.vulnerability import Package
from vulnsearch.report import to_toml_dict
from vulnsearch.sbom import search_vuln_in_sbom
from vulnsearch.search import (
    nvd_search_by_cpe,
    osv_search_by_cpe,
    search_by_cpe,
    search_cpe_by_keyword,
)

console = Console()


def _generate_toml(data: dict) -> None:
    """Prompt the user to generate and print a TOML."""
    if not click.confirm(f"Generate TOML for {data["name"]}?", default=False):
        return
    variables = {"variables": data}
    toml = tomli_w.dumps(variables)
    console.print(toml, markup=False)


def cpe_command(keyword: str) -> None:
    """Execute CPE search and render results."""
    search_results = search_cpe_by_keyword(keyword=keyword)

    if not search_results:
        console.print("[yellow]No vulnerabilities found[/yellow]")
        return

    print_cpe_table(search_results)


def sbom_command(file: FilePath, include_nvd: bool) -> dict | None:
    """Scan SBOM, render results and return TOML-ready data."""
    pkgs = search_vuln_in_sbom(file=file, include_nvd=include_nvd)

    if not pkgs:
        console.print("[yellow]No vulnerabilities found[/yellow]")
        return None

    for pkg in pkgs:
        print_vulns_table(pkg)

    return to_toml_dict(pkgs)


def search_command(
    name: str,
    version: str,
    ecosystem: str | None = None,
    source: str | None = None,
) -> dict | None:
    """Execute vulnerability search, render results and return TOML-ready data."""
    if source == "nvd":
        search_results = nvd_search_by_cpe(name=name, version=version)
    elif source == "osv":
        search_results = osv_search_by_cpe(
            name=name,
            version=version,
            ecosystem=ecosystem,
        )
    else:
        search_results = search_by_cpe(
            name=name,
            version=version,
            ecosystem=ecosystem,
        )

    if not search_results:
        console.print("[yellow]No vulnerabilities found[/yellow]")
        return None

    pkg = consolidate_vulnerabilities(name, version, search_results)
    print_vulns_table(pkg)
    return to_toml_dict(pkg)
