import json
import re
from typing import Any, Dict

from armorer.knowledge import KnowledgeBase


def _extract_first_json_fence(text: str) -> Dict[str, Any]:
    match = re.search(r"```json\s*(\{.*?\})\s*```", text, re.DOTALL)
    if not match:
        return {}
    try:
        parsed = json.loads(match.group(1))
        return parsed if isinstance(parsed, dict) else {}
    except Exception:
        return {}


def load_agent_hints(agent_name: str) -> Dict[str, Any]:
    """Load structured hints from KB topic markdown for a given agent name."""
    kb = KnowledgeBase()
    normalized = (agent_name or "").lower().strip()
    topics = kb.topics()

    candidates = []
    if normalized in topics:
        candidates.append(normalized)
    for t in topics:
        if normalized and normalized in t and t not in candidates:
            candidates.append(t)
    if not candidates:
        return {}

    # Prefer exact match first, then first fuzzy match.
    content = kb.get(candidates[0])
    if not content:
        return {}
    return _extract_first_json_fence(content)

