from __future__ import annotations

import json
import logging
import os
import re
from typing import Any, Dict

import yaml

logger = logging.getLogger(__name__)


def load_features(path: str = os.path.join("config", "features.yaml")) -> Dict[str, Any]:
    with open(path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}


def match_features(text: str, features_cfg: Dict[str, Any]) -> Dict[str, Any]:
    text_lower = text.lower() if text else ""
    result: Dict[str, Any] = {}
    for name, spec in features_cfg.items():
        hit = False
        keywords = [k.lower() for k in spec.get("keywords", [])]
        for kw in keywords:
            if kw in text_lower:
                hit = True
                break
        if not hit:
            for pattern in spec.get("regex", []) or []:
                try:
                    if re.search(pattern, text, flags=re.IGNORECASE):
                        hit = True
                        break
                except re.error as e:
                    logger.warning("bad regex for %s: %s", name, e)
        result[name] = bool(hit)
    return result


