"""What counts as a finding in an exported report.

Lives outside the router so the rule can be tested without standing up the
web stack, and so every report is forced through the same definition — the
reports drifted apart precisely because each one wrote its own query.
"""
from sqlalchemy.orm import Session

from app.models.vulnerability import Vulnerability

# The EOL check and the Nessus plugin importer both write findings with
# synthetic ids. They are real work items, but they are NOT CVEs, and counting
# them as such inflated every number past what the dashboard shows.
PSEUDO_PREFIXES = ("EOL-", "NESSUS-PLUGIN-")


def scoped(db: Session):
    """Real CVEs on assets that still exist.

    Reports used to query the table raw, so they counted findings on
    decommissioned and inactive assets — hosts the dashboard deliberately
    hides. An executive summary that disagrees with the screen it was exported
    from is worse than no summary, and the gap grows with every retired
    machine. Orphan findings (no asset at all) are kept, same as the dashboard.
    """
    from app.models.asset import Asset, AssetStatus
    q = (db.query(Vulnerability)
           .outerjoin(Asset, Vulnerability.asset_id == Asset.id)
           .filter((Asset.id.is_(None)) | (Asset.status == AssetStatus.ACTIVE)))
    for p in PSEUDO_PREFIXES:
        q = q.filter(~Vulnerability.cve_id.startswith(p))
    return q
