#!/usr/bin/env python3
"""Automated CVE lookup and markdown reporting tool.

Uses the public NVD CVE API for defensive vulnerability management. Respect API
rate limits and cache results for recurring scans.
"""

from __future__ import annotations

import argparse
from pathlib import Path

import requests


def query_cves(keyword: str, limit: int) -> list[dict[str, object]]:
    response = requests.get(
        "https://services.nvd.nist.gov/rest/json/cves/2.0",
        params={"keywordSearch": keyword, "resultsPerPage": limit},
        timeout=20,
    )
    response.raise_for_status()
    return response.json().get("vulnerabilities", [])


def main() -> int:
    parser = argparse.ArgumentParser(description="Create a CVE summary report for a product keyword.")
    parser.add_argument("keyword", help="Product, vendor, or package keyword")
    parser.add_argument("--limit", type=int, default=10)
    parser.add_argument("--output", type=Path, default=Path("cve_report.md"))
    args = parser.parse_args()

    vulns = query_cves(args.keyword, args.limit)
    lines = [f"# CVE Report: {args.keyword}", "", "Defensive vulnerability-management summary.", ""]
    for item in vulns:
        cve = item["cve"]
        metrics = cve.get("metrics", {})
        score = "n/a"
        for key in ["cvssMetricV31", "cvssMetricV30", "cvssMetricV2"]:
            if key in metrics:
                score = str(metrics[key][0]["cvssData"].get("baseScore", "n/a"))
                break
        description = cve.get("descriptions", [{}])[0].get("value", "No description")
        lines.extend([
            f"## {cve['id']}",
            f"- Published: {cve.get('published', 'unknown')}",
            f"- Last modified: {cve.get('lastModified', 'unknown')}",
            f"- CVSS score: {score}",
            f"- Summary: {description}",
            "- Analyst action: confirm asset exposure, patch availability, and compensating controls.",
            "",
        ])
    args.output.write_text("\n".join(lines), encoding="utf-8")
    print(f"Wrote {len(vulns)} CVE entries to {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
