"""Tests for analyzer module."""

import csv
from pathlib import Path

import pytest

from cve_extractor.core import analyze_distribution


@pytest.fixture
def sample_csv_file(tmp_path: Path) -> Path:
    """Create sample CSV file."""
    csv_file = tmp_path / "cves.csv"

    with open(csv_file, "w", encoding="utf-8", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["CVE ID", "CWE Type", "Description"])
        writer.writerow(["CVE-2024-1234", "CWE-79", "XSS vulnerability"])
        writer.writerow(["CVE-2024-5678", "CWE-89", "SQL injection"])
        writer.writerow(["CVE-2024-9012", "CWE-79", "Another XSS"])
        writer.writerow(["CVE-2023-1111", "CWE-20", "Input validation"])

    return csv_file


def test_analyze_distribution(sample_csv_file: Path) -> None:
    """Test analyzing CVE distribution."""
    result = analyze_distribution(sample_csv_file, min_count=0)

    assert result["total_cves"] == 4
    assert result["stats"]["CWE-79"] == 2
    assert result["stats"]["CWE-89"] == 1
    assert result["stats"]["CWE-20"] == 1

    # Year range
    assert result["year_range"] == (2023, 2024)

    # Most common
    assert result["most_common"] == ("CWE-79", 2)


def test_analyze_distribution_with_min_count(sample_csv_file: Path) -> None:
    """Test filtering by min_count."""
    result = analyze_distribution(sample_csv_file, min_count=2)

    assert result["total_cves"] == 4
    assert len(result["stats"]) == 1  # Only CWE-79 has count >= 2
    assert result["stats"]["CWE-79"] == 2


def test_analyze_distribution_nonexistent_file(tmp_path: Path) -> None:
    """Test with non-existent file."""
    nonexistent = tmp_path / "nonexistent.csv"

    with pytest.raises(ValueError, match="does not exist"):
        analyze_distribution(nonexistent)
