"""Rule Embeddings package -- Brain V6 Phase 1
Vectorizes brain rules via Ollama/sentence-transformers.
"""
from ._constants import EMBED_INDEX_FILE, EMBED_MODEL, OLLAMA_ENDPOINT, BRAIN_FILES
from .backends import embed_texts, cosine_similarity
_cosine_similarity = cosine_similarity  # backward compat alias (drift_detector imports this name)
from .index_ops import build_rule_index, search_similar, get_new_rules

__all__ = [
    "EMBED_INDEX_FILE", "EMBED_MODEL", "OLLAMA_ENDPOINT", "BRAIN_FILES",
    "embed_texts", "cosine_similarity", "_cosine_similarity", "build_rule_index", "search_similar", "get_new_rules",
]

if __name__ == "__main__":
    import json, logging, sys
    logging.basicConfig(level=logging.INFO, format="%(asctime)s [EMBED] %(message)s")
    if "--build" in sys.argv:
        print(json.dumps(build_rule_index(force="--force" in sys.argv, verbose=True), indent=2))
    elif "--search" in sys.argv:
        idx = sys.argv.index("--search")
        query = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        if not query:
            print("Usage: --search <query>")
            sys.exit(1)
        for r in search_similar(query, top_k=5):
            sim = r["similarity"]; src = r["source"]; txt = r["text"][:100]
            print(f"  [{sim:.3f}] ({src}) {txt}")
    elif "--status" in sys.argv:
        if EMBED_INDEX_FILE.exists():
            d = json.loads(EMBED_INDEX_FILE.read_text(encoding="utf-8"))
            rc = d.get("rule_count", 0); ba = d.get("built_at", "?")
            print(f"Rules: {rc}, Built: {ba}")
        else:
            print("No index found. Run --build first.")
    else:
        print("Usage: python -m pulse.brain.index.rule_embeddings [--build|--search <q>|--status]")
