#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""brain_db helpers: bulk_upsert and FTS search.

Split from brain_db.py for Law 7 compliance.
Uses lazy imports inside function bodies to avoid circular dependency with brain_db.py.
"""
from __future__ import annotations

from typing import Any, Dict, List


def bulk_upsert(table: str, items: list) -> int:
    """Bulk upsert items to SQLite. Returns count of successful writes."""
    from pulse.core.brain_db import upsert_knowledge  # lazy — avoids circular
    ok = 0
    for item in items:
        if upsert_knowledge(table, item):
            ok += 1
    return ok


def search(query: str, limit: int = 5) -> List[Dict[str, Any]]:
    """FTS5 text search. Returns [] on malformed query instead of raising."""
    from pulse.core.brain_db import get_conn  # lazy — avoids circular
    conn = get_conn()
    # S36: escape double-quotes to prevent FTS5 parse errors from special chars
    safe_query = query.replace(chr(34), chr(34) + chr(34))
    try:
        cur = conn.execute(
            "SELECT content, title, domain, agent, table_name, rank "
            "FROM knowledge_fts WHERE knowledge_fts MATCH ? ORDER BY rank LIMIT ?",
            (safe_query, limit))
        return [dict(r) for r in cur.fetchall()]
    except Exception:
        return []
