"""Verifier for sec-006: Dependency Vulnerability Check."""

import json
from pathlib import Path

import pytest


@pytest.fixture
def workspace(request):
    """Resolve the workspace path from the --workspace CLI flag."""
    return Path(request.config.getoption("--workspace"))


@pytest.fixture
def audit(workspace):
    """Load and return the dependency audit JSON."""
    path = workspace / "dependency_audit.json"
    assert path.exists(), "dependency_audit.json not found in workspace"
    data = json.loads(path.read_text())
    assert isinstance(data, list), "dependency_audit.json must contain a JSON array"
    return data


VULNERABLE_PACKAGES = {
    "flask": "CVE-2023-30861",
    "requests": "CVE-2023-32681",
    "django": "CVE-2023-31047",
    "pillow": "CVE-2023-44271",
    "urllib3": "CVE-2023-43804",
}

SAFE_PACKAGES = [
    "sqlalchemy", "numpy", "pyyaml", "jinja2", "cryptography",
    "werkzeug", "celery", "redis", "boto3", "paramiko",
]


def test_audit_file_exists(workspace):
    """dependency_audit.json must exist."""
    assert (workspace / "dependency_audit.json").exists()


def test_correct_number_of_vulnerable_packages(audit):
    """Should find exactly 5 vulnerable packages."""
    assert len(audit) == 5, f"Expected 5 vulnerable packages, got {len(audit)}"


def test_all_vulnerable_packages_found(audit):
    """All 5 vulnerable packages must be identified."""
    found = {entry["package"] for entry in audit}
    for pkg in VULNERABLE_PACKAGES:
        assert pkg in found, f"Vulnerable package '{pkg}' not detected"


def test_correct_cve_ids(audit):
    """Each vulnerable package must have the correct CVE ID."""
    for entry in audit:
        pkg = entry["package"]
        if pkg in VULNERABLE_PACKAGES:
            assert entry["cve_id"] == VULNERABLE_PACKAGES[pkg], (
                f"Wrong CVE for {pkg}: expected {VULNERABLE_PACKAGES[pkg]}, got {entry['cve_id']}"
            )


def test_safe_packages_not_flagged(audit):
    """Packages not in the vulnerable version range must not be flagged."""
    found = {entry["package"] for entry in audit}
    for pkg in SAFE_PACKAGES:
        assert pkg not in found, f"Safe package '{pkg}' incorrectly flagged"


def test_severity_levels_present(audit):
    """Each entry must have a valid severity level."""
    valid = {"critical", "high", "medium", "low"}
    for entry in audit:
        assert entry.get("severity") in valid, (
            f"Invalid severity for {entry['package']}: {entry.get('severity')}"
        )


def test_fixed_version_present(audit):
    """Each entry must include a fixed_version."""
    for entry in audit:
        assert "fixed_version" in entry and entry["fixed_version"], (
            f"Missing fixed_version for {entry['package']}"
        )


def test_django_is_critical(audit):
    """Django vulnerability should be rated critical."""
    django_entries = [e for e in audit if e["package"] == "django"]
    assert len(django_entries) == 1
    assert django_entries[0]["severity"] == "critical"


def test_each_entry_has_required_fields(audit):
    """Each entry must have all required fields."""
    required = {"package", "installed_version", "cve_id", "severity", "fixed_version", "description"}
    for entry in audit:
        for field in required:
            assert field in entry, f"Missing '{field}' in entry for {entry.get('package', 'unknown')}"
