"""Category suggestion helpers for registry tools."""

from __future__ import annotations

from pathlib import Path
from typing import Dict, List, Tuple

import yaml


def load_categories(categories_path: Path) -> List[Dict]:
    data = yaml.safe_load(categories_path.read_text(encoding="utf-8")) or {}
    return data.get("categories", [])


def suggest_categories(
    name: str,
    description: str,
    tags: List[str],
    categories_path: Path,
) -> List[Tuple[str, float]]:
    """Suggest categories ranked by confidence.

    Uses keyword matching against name/description/tags.
    Returns a list of (category_name, confidence).
    """
    categories = load_categories(categories_path)
    text = f"{name} {description} {' '.join(tags)}".lower()
    suggestions: List[Tuple[str, float]] = []

    for cat in categories:
        cat_name = cat.get("name")
        keywords = [str(k).lower() for k in cat.get("keywords", []) if k]
        if not cat_name or not keywords:
            continue
        hits = sum(1 for k in keywords if k in text)
        confidence = hits / max(len(keywords), 1)
        if hits:
            suggestions.append((cat_name, round(confidence, 3)))

    suggestions.sort(key=lambda item: item[1], reverse=True)
    return suggestions
