"""
Security-advisory awareness feed.

Independent of asset findings: a rolling view of what's being actively
exploited in the wild (CISA KEV), so operators see 0-days/exploited CVEs even
when no scanner has flagged an affected asset yet. Each entry is annotated
with whether we already have that CVE in inventory (and on how many assets).

Reuses the KEV catalog enrichment already fetches + caches (24h).
"""
from __future__ import annotations

import logging
from datetime import datetime
from typing import List, Optional

from sqlalchemy import func
from sqlalchemy.orm import Session

logger = logging.getLogger(__name__)


def _parse_date(s) -> Optional[datetime]:
    try:
        return datetime.strptime(str(s)[:10], "%Y-%m-%d")
    except (ValueError, TypeError):
        return None


def get_recent_kev(db: Session, limit: int = 20) -> List[dict]:
    """Most recently added CISA KEV entries, newest first, annotated with our
    inventory status. Returns [] on fetch failure (awareness is best-effort)."""
    from app.services.enrichment_service import fetch_kev_catalog
    try:
        kev = fetch_kev_catalog(db)
    except Exception as e:
        logger.warning("advisory: KEV fetch failed: %s", e)
        return []

    rows = []
    for cve, e in kev.items():
        rows.append({
            "cve_id": cve,
            "vendor": e.get("vendor"),
            "product": e.get("product"),
            "name": e.get("name"),
            "date_added": e.get("date_added"),
            "ransomware": bool(e.get("ransomware_use")),
            "description": e.get("short_description"),
        })
    rows.sort(key=lambda r: (_parse_date(r["date_added"]) or datetime.min), reverse=True)
    rows = rows[:limit]

    # Annotate with inventory presence in one query.
    from app.models.vulnerability import Vulnerability
    cves = [r["cve_id"] for r in rows]
    counts = {}
    if cves:
        q = (db.query(Vulnerability.cve_id, func.count(func.distinct(Vulnerability.asset_id)))
               .filter(Vulnerability.cve_id.in_(cves))
               .group_by(Vulnerability.cve_id))
        counts = {cve: n for cve, n in q.all()}
    for r in rows:
        r["asset_count"] = int(counts.get(r["cve_id"], 0))
        r["in_inventory"] = r["asset_count"] > 0
    return rows
