"""Security-advisory awareness feeds (CISA KEV + configurable RSS sources)."""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.user import User
from app.auth.dependencies import get_current_user, RequireEditor

router = APIRouter(prefix="/api/v1/advisories", tags=["Advisories"])


@router.get("/feeds")
def advisory_feeds(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """Cached security-advisory RSS feeds (ZDI / CERT-EU / BSI / ...). Served
    from the cache the scheduler fills; first call ever triggers a fetch."""
    from app.services.advisory_feed_service import get_cached_feeds, refresh_feeds
    cached = get_cached_feeds(db)
    if cached is None:
        refresh_feeds(db)
        cached = get_cached_feeds(db) or {"fetched_at": None, "feeds": []}
    return cached


@router.post("/feeds/refresh")
# Sync def → worker threadpool; N feed fetches are blocking I/O.
def refresh_advisory_feeds(
    db: Session = Depends(get_db),
    current_user: User = Depends(RequireEditor),
):
    """Re-fetch every enabled advisory feed now."""
    from app.services.advisory_feed_service import refresh_feeds
    return refresh_feeds(db)


@router.get("/kev-recent")
def kev_recent(
    limit: int = Query(20, le=100, description="How many recent KEV entries to return"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """Most recently added CISA KEV (actively-exploited) CVEs, newest first,
    annotated with whether we already have that CVE in inventory."""
    from app.services.advisory_service import get_recent_kev
    return {"items": get_recent_kev(db, limit=limit)}
