#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain item resolution for reward credit assignment."""
from __future__ import annotations


def _resolve_brain_items(title: str, domain: str) -> list:
    """Resolve task title to brain item IDs for reward credit assignment.

    Uses FTS MATCH first, falls back to LIKE for terms not in FTS index.
    """
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        words = [w for w in title.lower().split() if len(w) > 3][:8]
        item_ids = []
        for word in words:
            found = False
            # Try FTS MATCH first (fast)
            try:
                rows = conn.execute(
                    "SELECT item_id FROM knowledge_fts WHERE content MATCH ? LIMIT 3",
                    (word,)
                ).fetchall()
                for r in rows:
                    if r["item_id"] and r["item_id"] not in item_ids:
                        item_ids.append(r["item_id"])
                        found = True
            except Exception:
                pass
            # Fallback: LIKE search across brain tables
            if not found:
                for table in ("lessons", "failures", "patterns"):
                    try:
                        rows = conn.execute(
                            f"SELECT id FROM {table} WHERE content LIKE ? LIMIT 2",
                            (f"%{word}%",)
                        ).fetchall()
                        for r in rows:
                            if r["id"] and r["id"] not in item_ids:
                                item_ids.append(r["id"])
                    except Exception:
                        pass
        return item_ids[:20]
    except Exception:
        return []
