"""
Shared store metadata helpers for bluera-knowledge hooks.

Provides store loading and formatting for consistent, enticing
store presentation across all hook injection points.
"""

from __future__ import annotations

import json
import os
import re
from pathlib import Path


def get_stores_path() -> Path | None:
    """Get path to stores.json from project root."""
    project_root = os.environ.get("PROJECT_ROOT") or os.environ.get("PWD")
    if not project_root:
        return None
    return Path(project_root) / ".bluera" / "bluera-knowledge" / "data" / "stores.json"


def load_stores() -> list[dict]:
    """Load stores from stores.json. Returns empty list on error."""
    stores_path = get_stores_path()
    if stores_path is None or not stores_path.exists():
        return []
    try:
        with open(stores_path, encoding="utf-8") as f:
            data = json.load(f)
        if isinstance(data, dict):
            stores = data.get("stores", [])
            return stores if isinstance(stores, list) else []
        return data if isinstance(data, list) else []
    except (json.JSONDecodeError, IOError, OSError):
        return []


def _type_label(store_type: str) -> str:
    """Map store type to a human-readable label."""
    labels = {"repo": "source code", "file": "local docs", "web": "web docs"}
    return labels.get(store_type, store_type)


def normalize_name(name: str) -> str:
    """Normalize a library name for fuzzy matching.

    Handles: scoped packages (@scope/pkg → pkg), hyphens/underscores,
    case differences, trailing version suffixes.
    """
    n = name.lower().strip()
    # Strip scoped prefix: @scope/pkg → pkg
    n = re.sub(r"^@[^/]+/", "", n)
    # Normalize separators
    n = n.replace("-", "").replace("_", "").replace(".", "")
    # Strip trailing version-like suffix: pkg1.2.3 → pkg
    n = re.sub(r"\d+$", "", n)
    return n


def is_store_match(library_name: str, stores: list[dict]) -> str | None:
    """Check if a library name matches any indexed store.

    Returns the store name if matched, None otherwise.
    """
    lib_normalized = normalize_name(library_name)
    if not lib_normalized:
        return None
    for store in stores:
        store_name = store.get("name", "")
        if normalize_name(store_name) == lib_normalized:
            return store_name
    return None


def format_store_catalog(stores: list[dict], cap: int = 5) -> str:
    """Format stores into a compact enticing catalog string.

    Returns e.g. "react (source code), hono (source code), zod (source code)"
    Returns empty string if no stores.
    """
    if not stores:
        return ""
    names = []
    for s in stores[:cap]:
        name = s.get("name", "")
        stype = _type_label(s.get("type", ""))
        if name:
            names.append(f"{name} ({stype})")
    overflow = len(stores) - cap
    result = ", ".join(names)
    if overflow > 0:
        result += f" + {overflow} more"
    return result


def format_store_names(stores: list[dict], cap: int = 3) -> str:
    """Format store names only, ultra-compact for tight token budgets.

    Returns e.g. "react, hono, zod" or "react, hono, zod (+2 more)"
    Returns empty string if no stores.
    """
    if not stores:
        return ""
    names = [s.get("name", "") for s in stores[:cap] if s.get("name")]
    overflow = len(stores) - cap
    result = ", ".join(names)
    if overflow > 0:
        result += f" (+{overflow} more)"
    return result
