"""
Exploit-DB fetcher utilities.

Parses the public CSV index and filters rows that reference the given CVE in their "codes" field.
Returns a simplified list of dictionaries: {"id": str, "date": str}.
"""

from __future__ import annotations

import csv
from io import StringIO
from typing import Any, Dict, List, Optional, Tuple

from ..constants import EXPLOITDB_URL
from .common import fetch


def fetch_exploitdb_data(cve_id: str) -> Tuple[List[Dict[str, str]], Optional[str]]:
    """
    Fetch and parse the Exploit-DB CSV index, returning entries that include the CVE in the "codes" column.

    Returns (list_of_entries, None) or ([], error_message)
    """
    resp, err = fetch(EXPLOITDB_URL)
    if err:
        return [], err

    try:
        decoded = resp.content.decode("utf-8")  # type: ignore[attr-defined]
    except Exception as e:
        return [], f"❌ Error decoding CSV from Exploit-DB: {e}"

    try:
        reader = csv.DictReader(StringIO(decoded))
        results: List[Dict[str, str]] = []
        for row in reader:
            # Expected columns include: id, file, description, date, author, type, platform, port, codes, ...
            codes = (row.get("codes") or "").split(";")
            if cve_id in (code.strip() for code in codes):
                results.append({"id": row.get("id", ""), "date": row.get("date", "")})
        return results, None
    except Exception as e:
        return [], f"❌ Error parsing CSV data from Exploit-DB: {e}"
