"""v0.10 Phase H · 资料库增强门控 — 默认关，超阈值可自动开，mode=off 永不自动开。"""

from __future__ import annotations

from typing import Any

FEATURE_FTS = "fts"
FEATURE_INCREMENTAL_SYNC = "incremental_sync"
DEFAULT_AUTO_ENABLE_ABOVE = 500


def _enhancements_cfg(config: dict[str, Any] | None) -> dict[str, Any]:
    vault = (config or {}).get("vault") or {}
    enh = vault.get("enhancements")
    return dict(enh) if isinstance(enh, dict) else {}


def vault_entry_count(index: dict[str, Any]) -> int:
    entries = index.get("entries") or []
    return sum(1 for e in entries if isinstance(e, dict) and e.get("vault_id"))


def enhancement_mode(config: dict[str, Any] | None, feature: str) -> str:
    feat = _enhancements_cfg(config).get(feature) or {}
    if not isinstance(feat, dict):
        return "auto"
    mode = str(feat.get("mode") or "auto").strip().lower()
    if mode in ("on", "off", "auto"):
        return mode
    return "auto"


def auto_enable_above(config: dict[str, Any] | None) -> int:
    enh = _enhancements_cfg(config)
    try:
        return max(1, int(enh.get("auto_enable_above", DEFAULT_AUTO_ENABLE_ABOVE)))
    except (TypeError, ValueError):
        return DEFAULT_AUTO_ENABLE_ABOVE


def enhancement_active(
    config: dict[str, Any] | None,
    feature: str,
    *,
    entry_count: int,
) -> bool:
    """mode=on 恒开 · mode=off 恒关（不自动开）· mode=auto 仅 entry_count≥阈值时开。"""
    mode = enhancement_mode(config, feature)
    if mode == "on":
        return True
    if mode == "off":
        return False
    return entry_count >= auto_enable_above(config)


def enhancement_status(config: dict[str, Any] | None, *, entry_count: int) -> dict[str, Any]:
    threshold = auto_enable_above(config)
    out: dict[str, Any] = {
        "entry_count": entry_count,
        "auto_enable_above": threshold,
        "features": {},
    }
    for feat in (FEATURE_FTS, FEATURE_INCREMENTAL_SYNC):
        mode = enhancement_mode(config, feat)
        active = enhancement_active(config, feat, entry_count=entry_count)
        out["features"][feat] = {"mode": mode, "active": active}
    return out
