"""Report scope + ranking — run: python tests/test_report_scope.py

Two things the reports got wrong silently, so both are pinned here:

1. Scope. They queried the table raw, counting findings on decommissioned
   assets and counting EOL-/NESSUS-PLUGIN- pseudo-CVEs as CVEs — so the
   exported numbers disagreed with the dashboard for the same estate.
2. "Top Priority Risks" had a LIMIT and no ORDER BY, so the five rows under
   that heading were whichever five the database felt like returning.

Checked by reading the emitted SQL — no database needed.
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.models.vulnerability import Vulnerability, VulnerabilitySeverity, VulnerabilityStatus
from app.services.report_scope import scoped as _scoped


def _sql(q):
    return str(q.statement.compile(compile_kwargs={"literal_binds": True})).lower()


def demo():
    from sqlalchemy.orm import Session
    from sqlalchemy import create_engine
    engine = create_engine("sqlite://")
    db = Session(engine)

    sql = _sql(_scoped(db))
    # Inactive/decommissioned assets are excluded, orphans (no asset) kept.
    assert "left outer join assets" in sql
    assert "active" in sql
    assert "assets.id is null" in sql
    # Pseudo-CVEs excluded by prefix.
    assert "eol-" in sql and "nessus-plugin-" in sql

    # The ranked query really carries an ORDER BY — the bug was its absence.
    top = (_scoped(db)
           .filter(Vulnerability.severity == VulnerabilitySeverity.critical,
                   Vulnerability.status == VulnerabilityStatus.open)
           .order_by(Vulnerability.priority_score.desc().nullslast())
           .limit(5))
    tsql = _sql(top)
    assert "order by" in tsql and "priority_score desc" in tsql
    assert "limit 5" in tsql

    db.close()
    print("report scope OK")


if __name__ == "__main__":
    demo()
