"""
CVE distribution analysis module.

Provides functions to analyze CVE distribution by CWE type and year.
"""

import csv
import logging
from collections import Counter
from pathlib import Path

logger = logging.getLogger(__name__)


def analyze_distribution(csv_file: Path, min_count: int = 0) -> dict:
    """
    Analyze CVE distribution by CWE type from CSV file.

    Parses CSV file generated by extract_cves_to_csv, groups by CWE type,
    and calculates statistics.

    Args:
        csv_file: Path to CSV file with CVE data
        min_count: Minimum count threshold for including CWE types in stats

    Returns:
        Dict with keys:
            - total_cves: Total CVE count
            - stats: Dict[str, int] mapping CWE type to count (filtered by min_count)
            - year_range: Tuple[int, int] of (earliest_year, latest_year) or None
            - most_common: Tuple[str, int] of (most_common_cwe, count) or None

    Raises:
        ValueError: csv_file is None or does not exist
        OSError: File read error
    """
    if not csv_file:
        raise ValueError("csv_file cannot be None")

    if not csv_file.exists():
        raise ValueError(f"CSV file does not exist: {csv_file}")

    logger.info("Analyzing CVE distribution from: %s", csv_file)

    cwe_counter: Counter[str] = Counter()
    year_set: set[int] = set()
    total_cves = 0

    try:
        with open(csv_file, encoding="utf-8") as f:
            reader = csv.DictReader(f)

            for row in reader:
                total_cves += 1
                cwe_type = row.get("CWE Type", "Unknown")
                cwe_counter[cwe_type] += 1

                # Extract year from CVE ID (CVE-YYYY-XXXXX format)
                cve_id = row.get("CVE ID", "")
                if cve_id and cve_id.startswith("CVE-"):
                    parts = cve_id.split("-")
                    if len(parts) >= 2:
                        try:
                            year = int(parts[1])
                            year_set.add(year)
                        except ValueError:
                            pass

    except OSError as e:
        raise OSError(f"Failed to read CSV file {csv_file}: {e}") from e

    # Filter stats by min_count
    stats = {cwe: count for cwe, count in cwe_counter.items() if count >= min_count}

    # Calculate year range
    year_range = (min(year_set), max(year_set)) if year_set else None

    # Find most common CWE
    most_common = cwe_counter.most_common(1)[0] if cwe_counter else None

    logger.info(
        "Analyzed %d CVEs: %d unique CWE types, year range %s",
        total_cves,
        len(stats),
        year_range,
    )

    return {
        "total_cves": total_cves,
        "stats": stats,
        "year_range": year_range,
        "most_common": most_common,
    }
