#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Cross-Agent Learning: Extract lessons from other agents (U7: Dr. Mirror Neurons).

Enables agents to learn from each other's experiences without direct communication.
Scans lessons/failures for entries from OTHER agents and surfaces them at boot.

Dependencies: Python stdlib + brain_utils (internal)
"""

import re

from pulse.core.brain_utils import (
    LESSONS_FILE, FAILS_FILE, LESSONS_JSONL, FAILS_JSONL, read_jsonl_entries,
)

_AGENT_TAG = re.compile(r"(?:source|agent)[:\s]*(\w+)", re.IGNORECASE)
_KNOWN_AGENTS = {"claude", "gemini", "codex", "grok", "worker"}


def format_agent_tag(text: str) -> str:
    """Extract agent name from a search hit or lesson text."""
    m = _AGENT_TAG.search(text)
    if m:
        name = m.group(1).lower()
        if any(a in name for a in _KNOWN_AGENTS):
            return name
    return ""


def extract_cross_agent_intel(current_agent: str = "", limit: int = 5) -> list:
    """Find lessons/failures from OTHER agents for cross-pollination.

    Returns list of strings like "[GEMINI] lesson text here".
    Tries JSONL first (structured agent field), falls back to MD.
    """
    current = current_agent.lower() if current_agent else ""
    intel = []

    # JSONL fast-path: structured agent field
    for jsonl_file in [LESSONS_JSONL, FAILS_JSONL]:
        for entry in read_jsonl_entries(jsonl_file):
            agent = entry.get("agent", "")
            if not agent:
                # Try to detect from content
                agent = format_agent_tag(entry.get("content", ""))
            else:
                agent = agent.lower()
                if not any(a in agent for a in _KNOWN_AGENTS):
                    agent = ""
            if not agent or (current and current in agent):
                continue
            title = entry.get("title", "") or entry.get("content", "")[:100]
            intel.append(f"[{agent.upper()}] {title[:100]}")
            if len(intel) >= limit:
                return intel

    if intel:
        return intel

    # MD fallback
    for md_file in [LESSONS_FILE, FAILS_FILE]:
        if not md_file.exists():
            continue
        text = md_file.read_text(encoding="utf-8", errors="replace")
        sections = text.split("\n## ")
        for section in sections[1:]:
            lines = section.strip().split("\n")
            title = lines[0].strip()
            body = "\n".join(lines[1:5])  # First few lines for agent detection
            agent = format_agent_tag(body) or format_agent_tag(title)
            if not agent or (current and current in agent):
                continue
            intel.append(f"[{agent.upper()}] {title[:100]}")
            if len(intel) >= limit:
                return intel

    return intel
