# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Session context formatting — SoC split from session_lifecycle."""
from __future__ import annotations
from datetime import datetime, timezone
from pulse.brain.session.session_lifecycle import get_recent_sessions


def build_recent_sessions_context(limit: int = 3) -> str:
    """Build a formatted string of recent sessions for boot injection.

    Returns empty string if no sessions exist.
    """
    sessions = get_recent_sessions(limit=limit)
    if not sessions:
        return ""

    lines = ["## RECENT SESSIONS (Cross-Agent Memory)"]
    for s in sessions:
        ts = s.get("started_at", "")[:19]
        agent = s.get("agent", "unknown")
        summary = s.get("summary", "")[:200]
        intent = s.get("user_intent", "")[:100]
        turns = s.get("turn_count", 0)
        status = s.get("status", "?")

        try:
            started = datetime.fromisoformat(ts.replace("Z", "+00:00"))
            if started.tzinfo is None:
                started = started.replace(tzinfo=timezone.utc)
            delta = datetime.now(timezone.utc) - started
            if delta.total_seconds() < 3600:
                age = f"{int(delta.total_seconds() / 60)}m ago"
            elif delta.total_seconds() < 86400:
                age = f"{int(delta.total_seconds() / 3600)}h ago"
            else:
                age = f"{int(delta.days)}d ago"
        except Exception:
            age = ts

        line = f"  [{age}] {agent}: "
        if intent:
            line += f'"{intent}"'
        elif summary:
            line += summary
        else:
            line += f"({turns} turns, {status})"
        lines.append(line)

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