#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Search Source: Episodic Index (Symposium P1 — Phase 3)

Searches episodic_index.json for conversations matching a query.
Returns salience-scored results matching the brain_search contract.

Dependencies: Python stdlib + episodic_index (Law 4)
"""

from pulse.brain.episodic_index import EPISODIC_INDEX_FILE, load_index


def search_episodic(query: str, config: dict = None) -> list:
    """Search episodic index by entity, keyword, or agent name."""
    if not EPISODIC_INDEX_FILE.exists():
        return []

    index = load_index()
    if not index:
        return []

    query_lower = query.lower().strip()
    if not query_lower:
        return []

    query_words = set(query_lower.split())
    hits = []

    for entry in index:
        score = 0.0
        entities = [e.lower() for e in entry.get("entities_mentioned", [])]
        keywords = entry.get("topic_keywords", [])
        summary = entry.get("summary", "").lower()
        agent = entry.get("agent", "")

        # Entity match (strongest)
        for entity in entities:
            if entity in query_lower or query_lower in entity:
                score += 3.0
                break

        # Keyword overlap
        kw_set = set(keywords)
        overlap = len(query_words & kw_set)
        score += overlap * 0.5

        # Summary text match
        for qw in query_words:
            if len(qw) > 2 and qw in summary:
                score += 0.3

        # Agent name match ("what did claude say about X")
        if agent in query_lower:
            score += 1.0

        if score < 0.5:
            continue

        # Build hit
        salience = min(score * 0.8, 10.0)
        entities_display = entry.get("entities_mentioned", [])[:5]
        ts = entry.get("timestamp", "")[:19]

        hits.append({
            "text": f"[{ts}] {agent}: {entry.get('summary', '')[:80]}",
            "title": f"[EPISODE] {entry.get('summary', '')[:60]}",
            "salience": round(salience, 3),
            "confidence": 0.8,
            "source": "episodic",
            "agent": agent,
            "timestamp": entry.get("timestamp", ""),
            "entities": entities_display,
            "emotional_intensity": entry.get("emotional_intensity", 0),
        })

    hits.sort(key=lambda h: h["salience"], reverse=True)
    return hits[:10]
