# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Support helpers for brain boot loaders (private helpers + secondary loaders)."""
from __future__ import annotations
import json

from pulse.core.brain_utils import (
    HIPPOCAMPUS_DIR,
    LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL,
    load_json_dict,
    _extract_jsonl_titles as extract_jsonl_titles,
)
from pulse.core.paths import get_state_dir
from pulse.brain.brain_search import brain_search


def _clean_titles(titles: list, limit: int = 10) -> list:
    seen = set()
    clean = []
    for h in titles:
        h = h.strip().lstrip("*").strip()
        if len(h) < 15:
            continue
        if h.startswith("/") or h.startswith("\\") or h.startswith("C:"):
            continue
        key = h.lower()[:40]
        if key not in seen:
            seen.add(key)
            clean.append(h[:80])
    return clean[-limit:]


def _get_confirmed_titles(table: str, limit: int = 5) -> list[str]:
    """Get CONFIRMED items (conf>=0.75, ec>=3, valid). Ground truth anchors."""
    import sqlite3
    try:
        from pulse.core.brain_db import DB_PATH
        conn = sqlite3.connect(str(DB_PATH.resolve()), timeout=2)
        conn.row_factory = sqlite3.Row
        try:
            rows = conn.execute(
                f"SELECT title FROM {table} WHERE source_type='CONFIRMED' AND confidence>=0.75"
                f" AND evidence_count>=3 AND validity='valid' ORDER BY confidence DESC LIMIT ?",
                (limit,)).fetchall()
            return _clean_titles([r[0] if isinstance(r, (tuple, list)) else r["title"] for r in rows], limit=limit) if rows else []
        finally:
            conn.close()
    except Exception:
        return []


def _get_recent_titles(table: str, limit: int = 10) -> list[str] | None:
    """Get most recent titles from SQLite (sub-ms vs 11.3MB JSONL scan).

    Returns list of cleaned titles on success, None on failure (triggers JSONL fallback).
    """
    import sqlite3
    try:
        from pulse.core.brain_db import DB_PATH
        conn = sqlite3.connect(str(DB_PATH.resolve()), timeout=2)
        conn.row_factory = sqlite3.Row
        try:
            rows = conn.execute(
                f"SELECT title FROM {table} ORDER BY timestamp DESC LIMIT ?",
                (limit,)
            ).fetchall()
            if rows:
                titles = [r[0] if isinstance(r, (tuple, list)) else r["title"] for r in rows]
                return _clean_titles(titles, limit=limit)
        finally:
            conn.close()
    except Exception:
        pass
    return None


def _load_jsonl_titles(jsonl_path, limit: int = 10) -> list[str]:
    """Fallback: load titles from JSONL using shared extractor (scans full file)."""
    items = extract_jsonl_titles(jsonl_path, max_chars=80, min_chars=15)
    titles = [item["title"] for item in items]
    return _clean_titles(titles, limit=limit)


def _extract_search_hits(hits, limit: int = 5) -> list:
    out = []
    for h in hits[:limit]:
        text = (h.get("text") or h.get("title", ""))[:80].strip()
        if text and len(text) > 10:
            out.append(text)
    return out


def _load_cross_agent_intel(current_agent: str = "", limit: int = 5) -> list:
    """Load lessons/failures from OTHER agents for cross-pollination (U7)."""
    try:
        from pulse.brain.session.cross_agent import extract_cross_agent_intel
        return extract_cross_agent_intel(current_agent, limit)
    except Exception:
        return []


def load_curriculum(domain: str = "", task_query: str = "") -> dict:
    """Load domain curriculum from D15 Phylogenetic Skill Compiler output.

    Tries direct domain match first, then infers from task_query keywords.
    Returns curriculum dict or {} if unavailable.
    """
    curricula_file = HIPPOCAMPUS_DIR / "Semantic" / "curricula.json"
    if not curricula_file.exists():
        return {}
    try:
        data = load_json_dict(curricula_file)
        cur = data.get("curricula", {})
        if not cur:
            return {}
        # Direct domain match
        if domain and domain.lower() in cur:
            result = cur[domain.lower()]
            result["_generation"] = data.get("generation", 0)
            return result
        # Infer from task_query keywords
        if task_query:
            query_lower = task_query.lower()
            for d, c in cur.items():
                if d in query_lower:
                    c["_generation"] = data.get("generation", 0)
                    return c
        return {}
    except Exception:
        return {}


def _search_brain_for_task(task_title: str) -> dict:
    """Lightweight brain search for task context."""
    # Skip embeddings at boot — 177MB index parse adds ~25s
    return brain_search(task_title, max_per_source=2, exclude_sources={"embeddings"}) if brain_search else {}


def load_session_continuity(agent: str = "claude") -> str:
    """P2-4: Load prior session checkpoint and return a ## PREVIOUS SESSION STATE section.

    Called during boot. If a checkpoint < 24h old exists for this agent, injects
    the task, progress, findings, and files_touched so the agent resumes with context.
    Returns empty string if no recent checkpoint exists.
    """
    try:
        from pulse.brain.session.session_checkpoint import load_latest_checkpoint
        cp = load_latest_checkpoint(agent)
        if not cp:
            return ""
        lines = ["## PREVIOUS SESSION STATE"]
        lines.append(f"Task:     {cp.get('task', 'unknown')[:100]}")
        lines.append(f"Progress: {cp.get('progress', 'unknown')[:120]}")
        findings = cp.get("findings", [])
        if findings:
            lines.append("Findings:")
            for f in findings[:5]:
                lines.append(f"  - {str(f)[:100]}")
        files = cp.get("files_touched", [])
        if files:
            lines.append(f"Files touched: {', '.join(str(f)[:60] for f in files[:5])}")
        ts = cp.get("timestamp", "")[:19]
        lines.append(f"Saved: {ts} UTC")
        return "\n".join(lines)
    except Exception:
        return ""


def load_swarm_competence() -> str:
    """Phase 5E: Theory of Mind — agent strength/weakness profiles."""
    try:
        hf = get_state_dir() / "hebbian_matrix.json"
        if not hf.exists():
            return ""
        data = json.loads(hf.read_text(encoding="utf-8"))
        if not data:
            return ""
        lines = ["Agent Competence Profile:"]
        for aid, doms in data.get("matrix", {}).items():
            if not isinstance(doms, dict):
                continue
            ents = []
            for d, s in doms.items():
                if not isinstance(s, dict):
                    continue
                att = s.get("successes", 0) + s.get("failures", 0)
                if att >= 3:
                    ents.append((d, s.get("successes", 0) / att, att))
            if ents:
                ents.sort(key=lambda x: -x[1])
                parts = [f"{int(r*100)}% on {d} ({a} tasks)" for d, r, a in ents[:3]]
                lines.append(f"- {aid}: {', '.join(parts)}")
        return "\n".join(lines) if len(lines) > 1 else ""
    except Exception:
        return ""
