"""Backfill exploitation_source for SSVC-only override rows

Revision ID: 022
Revises: 021
Create Date: 2026-05-20 11:00:00.000000

Earlier override-service runs wrote SSVC fields (ssvc_technical_impact,
ssvc_automatable, exploitation_status) without setting
exploitation_source. The pin only happened when CVSS or severity
changed.

Result: operator filter
  WHERE exploitation_source='vulnrichment' AND exploitation_status != 'none'
under-reported by orders of magnitude (4 vs ~840 in tester's DB).

Stamp those rows as vulnrichment-sourced so the filter works. Only
touch rows that have at least one Vulnrichment-supplied SSVC field
AND no exploitation_source yet — does not overwrite an existing
source label (e.g. nvd / cvelistv5 / manual).

Idempotent — second run finds no candidates.
"""
from alembic import op


revision = '022'
down_revision = '021'
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute("""
        UPDATE vulnerabilities
        SET exploitation_source = 'vulnrichment'
        WHERE exploitation_source IS NULL
          AND (
              exploitation_status IS NOT NULL
              OR ssvc_technical_impact IS NOT NULL
              OR ssvc_automatable IS NOT NULL
          )
    """)


def downgrade() -> None:
    # Cannot reliably distinguish backfilled rows from real vulnrichment
    # writes, so the downgrade is a no-op.
    pass
