"""Threat-intelligence feature module.

This module owns local ThreatDB loading primitives.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Optional


def _load_json(path: Path) -> Optional[dict]:
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None


def load_threat_hashes(threat_db_path: Path) -> tuple[set[str], dict]:
    """Load known-bad SHA-256 hashes and feed metadata from local ThreatDB."""
    hashes: set[str] = set()
    feeds_meta: dict = {}

    feeds_meta_path = threat_db_path / "feeds-metadata.json"
    meta = _load_json(feeds_meta_path)
    if isinstance(meta, dict):
        feeds_meta = meta

    hashes_dir = threat_db_path / "hashes"
    if hashes_dir.exists() and hashes_dir.is_dir():
        for item in hashes_dir.rglob("*"):
            if not item.is_file():
                continue
            try:
                for raw in item.read_text(encoding="utf-8", errors="ignore").splitlines():
                    line = raw.strip()
                    if not line or line.startswith("#"):
                        continue
                    token = line.split(",")[0].split()[0].strip().lower()
                    if len(token) == 64 and all(c in "0123456789abcdef" for c in token):
                        hashes.add(token)
            except OSError:
                continue

    return hashes, feeds_meta
