from pathlib import Path

import click
from pydantic import FilePath

from vulnsearch.cli.commands import (
    _generate_toml,
    cpe_command,
    sbom_command,
    search_command,
)


@click.group()
def cli() -> None:
    """Vulnerability search CLI."""


@cli.command()
@click.argument("keyword")
def cpe(keyword: str) -> None:
    """
    Search for CPE matches using a product keyword.
    """
    cpe_command(keyword=keyword)


@cli.command()
@click.argument("file", type=click.Path(path_type=Path, exists=True, dir_okay=False))
@click.option("--include-nvd", is_flag=True, help="Extend the search to include NVD.")
def sbom(file: FilePath, include_nvd: bool) -> None:
    """Scan an SBOM file."""
    data = sbom_command(file=file, include_nvd=include_nvd)
    for d in data:
        _generate_toml(d)


@cli.command()
@click.argument("name")
@click.option("-v", "--version", required=True)
@click.option("-e", "--ecosystem", default=None)
@click.option("-s", "--source", type=click.Choice(["nvd", "osv"], case_sensitive=False))
def search(name: str, version: str, ecosystem: str | None, source: str | None) -> None:
    """Search vulnerabilities by name/version/ecosystem."""
    data = search_command(
        name=name, version=version, ecosystem=ecosystem, source=source
    )
    _generate_toml(data[0])
