"""
CVE filtering and loading module.

Provides functions to load CVE JSON files into CVERecord objects.
"""

import json
import logging
from pathlib import Path

from .models import CVERecord

logger = logging.getLogger(__name__)


def load_cves_from_directory(cve_dir: Path) -> list[CVERecord]:
    """
    Load all CVE JSON files from directory into CVERecord objects.

    Scans directory recursively for .json files, attempts to load each
    via CVERecord.load_from_file(). Skips malformed files with warning log.

    Args:
        cve_dir: Directory containing CVE JSON files

    Returns:
        List of successfully loaded CVERecord objects (may be empty)

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

    if not cve_dir.exists():
        raise ValueError(f"Directory does not exist: {cve_dir}")

    if not cve_dir.is_dir():
        raise ValueError(f"Path is not a directory: {cve_dir}")

    logger.info("Loading CVEs from: %s", cve_dir)

    cve_records = []
    json_files = list(cve_dir.rglob("*.json"))

    if not json_files:
        logger.warning("No JSON files found in: %s", cve_dir)
        return []

    for json_file in json_files:
        try:
            cve = CVERecord.load_from_file(json_file)
            cve_records.append(cve)
        except (OSError, ValueError, KeyError, json.JSONDecodeError) as e:
            logger.debug("Skipping non-CVE or malformed JSON file %s: %s", json_file, e)
            continue

    logger.info("Loaded %d CVE records from %d files", len(cve_records), len(json_files))
    return cve_records
