# ClawTex — Brain Startup / Blackout Recovery
# Forged by DeVere Cooley — BB4C — "Breath Before Code"

"""
Startup recall and blackout recovery for ClawTex agents.

Provides:
  on_start(client, namespace)  →  Pull recent context on agent init
  format_startup_context(memories)  →  Format memories into system prompt block

ClawTexAgent calls `await memory.on_start()` during initialization.
This ensures that after any blackout or restart, the agent knows
what it was working on — automatically.

BB4C: memory before action. Always.
"""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .mandeldb import MandelDBClient

logger = logging.getLogger(__name__)

# Queries run at startup to restore context
_STARTUP_QUERIES = [
    "who is the operator user who built this system, their identity name email",
    "what were we working on recently, latest projects and tasks",
    "open threads decisions pending actions",
    "what happened in the last session",
]

_MAX_MEMORIES = 10
_MAX_CONTENT_LEN = 500


async def on_start(
    client: "MandelDBClient",
    namespace: str | None = None,
    top_k: int = 8,
) -> str:
    """
    Pull recent memories from MandelDB on agent startup.

    Returns a formatted markdown block suitable for injection into the system prompt.
    Empty string if no memories found or if MandelDB is unreachable (fail-open).
    """
    all_results: list[dict] = []
    seen: set[str] = set()

    for query in _STARTUP_QUERIES:
        try:
            results = await client.recall(query=query, top_k=top_k, namespace=namespace)
            for r in results:
                # Deduplicate by content prefix
                key = (r.get("content") or r.get("text") or "")[:60]
                if key and key not in seen:
                    seen.add(key)
                    all_results.append(r)
        except Exception as exc:  # noqa: BLE001
            # Fail open — a missing brain shouldn't stop the agent
            logger.warning("Brain startup recall failed for query '%s': %s", query, exc)

    if not all_results:
        logger.info("Brain startup: no memories found (clean slate or MandelDB unreachable)")
        return ""

    # Sort by relevance score
    all_results.sort(key=lambda x: x.get("score", 0.0), reverse=True)

    context = format_startup_context(all_results[:_MAX_MEMORIES])
    logger.info("Brain startup: restored %d memories from MandelDB", len(all_results))
    return context


def format_startup_context(memories: list[dict]) -> str:
    """
    Format a list of MandelDB memory objects into a system prompt block.

    Injected before agent SOUL.md so memories inform every response.
    """
    if not memories:
        return ""

    timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    lines = [
        "## 🧠 Restored Memory — Brain Reconnect",
        f"*Context recovered from MandelDB at {timestamp}*",
        "",
        "The following memories were restored after session start. "
        "Use them to pick up where things left off:",
        "",
    ]

    for i, mem in enumerate(memories, 1):
        content = (mem.get("content") or mem.get("text") or "").strip()
        if not content:
            continue
        if len(content) > _MAX_CONTENT_LEN:
            content = content[:_MAX_CONTENT_LEN] + "…"
        score = mem.get("score")
        score_str = f" [{score:.2f}]" if isinstance(score, float) else ""
        lines.append(f"{i}.{score_str} {content}")

    lines.append("")
    return "\n".join(lines)
