#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""UI formatters for the agent boot briefing."""
from __future__ import annotations
import re
from datetime import datetime, timedelta, timezone

def _recency_tag(item: str) -> str:
    """Add a recency tag (e.g., [2h ago]) if a timestamp is found."""
    match = re.search(r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})", item)
    if not match:
        return ""
    try:
        ts = datetime.fromisoformat(match.group(1).replace("Z", "+00:00"))
        delta = datetime.now(timezone.utc) - ts
        if delta < timedelta(minutes=60):
            return f"[{int(delta.total_seconds() / 60)}m ago]"
        if delta < timedelta(hours=24):
            return f"[{int(delta.total_seconds() / 3600)}h ago]"
    except Exception:
        pass
    return ""

def build_brain_briefing(brain_data: dict, task_search: dict) -> str:
    """Build the MANDATORY BRAIN BRIEFING — injected into every agent's context."""
    lines = ["", "=" * 60, "MANDATORY BRAIN BRIEFING — READ BEFORE ANY ACTION", "=" * 60, ""]

    ap = brain_data.get("anti_patterns", [])
    if ap:
        lines.append("## NEVER DO THIS (Anti-Patterns)")
        lines.extend([f"  X  {item}" for item in ap])
        lines.append("")

    confirmed_gt = brain_data.get("confirmed_ground_truth", [])
    if confirmed_gt:
        lines.append("## GROUND TRUTH [CONFIRMED]")
        lines.extend([f"  ✓  {item}" for item in confirmed_gt])
        lines.append("")

    profile = brain_data.get("user_profile", {})
    if profile:
        lines.append("## YOUR PROFILE (Distilled from Wants/Dont_Wants)")
        for key, principles in profile.items():
            if principles:
                lines.append(f"  - **{key.replace('_', ' ').title()}:**")
                lines.extend([f"    - {p}" for p in principles[:3]])
        lines.append("")

    fails = brain_data.get("failures", [])
    if fails:
        lines.append("## RECENT FAILURES (Don't Repeat)")
        lines.extend([f"  !  {_recency_tag(item) + ' ' if _recency_tag(item) else ''}{item}" for item in fails[-5:]])
        lines.append("")

    lessons = brain_data.get("lessons", [])
    if lessons:
        lines.append("## LESSONS LEARNED (Apply These)")
        lines.extend([f"  >  {item}" for item in lessons[-5:]])
        lines.append("")

    patterns = brain_data.get("patterns", [])
    if patterns:
        lines.append("## PROVEN PATTERNS (Use These)")
        lines.extend([f"  *  {item}" for item in patterns[-5:]])
        lines.append("")

    decisions = brain_data.get("decisions", [])
    if decisions:
        lines.append("## PAST DECISIONS (Active Choices)")
        lines.extend([f"  @  {item}" for item in decisions[:5]])
        lines.append("")

    working_memory = brain_data.get("working_memory_context", [])
    if working_memory:
        lines.append("## WORKING MEMORY (Recent Context)")
        lines.extend([f"  * {item}" for item in working_memory])
        lines.append("")

    # P47: Recent sessions (cross-agent context)
    recent_sessions = brain_data.get("recent_sessions_text", "")
    if recent_sessions:
        lines.append(recent_sessions)

    # Task-specific insights from task_search
    if task_search and task_search.get("total_results", 0) > 0:
        lines.append("Task-Specific Insights:")
        for src, hits in task_search.get("results", {}).items():
            if isinstance(hits, list):
                for h in hits[:2]:
                    t = h.get("title") or h.get("content") or h.get("text") or ""
                    if t:
                        lines.append(f"  * {t[:120]}")

    agent_procs = brain_data.get("agent_procedures", {})
    if agent_procs:
        weak = agent_procs.get("weak_domains", [])
        procs = agent_procs.get("procedures", [])
        if weak:
            lines.append("## YOUR WEAK SPOTS (Agent-Specific)")
            for d in weak[:3]:
                lines.append(f"  !  {d['domain']}: {d['success_rate']:.0%} success ({d['total']} tasks)")
            lines.append("")
        if procs:
            lines.append("## RECOMMENDED PROCEDURES (Tailored For You)")
            for p in procs[:5]:
                ghost_tag = f"[GHOST: {p['ghost_agent']}] " if p.get("ghost_agent") else ""
                lines.append(f"  >  {ghost_tag}{p['name']} (domain: {p['domain']}, confidence: {p['confidence']:.0%})")
                for i, step in enumerate(p.get("steps", [])[:4], 1):
                    lines.append(f"    {i}. {step}")
            lines.append("")

    constraints = brain_data.get("synthetic_constraints", [])
    if constraints:
        lines.append("## GUARDRAILS (Conflict-Predicted Constraints)")
        for c in constraints[:5]:
            lines.append(f"  X  {c['constraint']} (conf: {c['confidence']:.0%})")
            if c.get("reason"):
                lines.append(f"     Reason: {c['reason']}")
        lines.append("")

    gate_feedback = brain_data.get("gate_feedback", [])
    if gate_feedback:
        lines.append("## RECENT GATE FAILURES (Swarm Anti-Patterns — Temporary)")
        for gf in gate_feedback[:5]:
            lines.append(f"  !!  [{gf.get('failure_type', '?')}] {gf.get('anti_pattern', '?')}")
            if gf.get("corrective_constraint"):
                lines.append(f"      Fix: {gf['corrective_constraint']}")
        lines.append("")

    curriculum = brain_data.get("curriculum", {})
    if curriculum and curriculum.get("learning_path"):
        gen = curriculum.get("_generation", curriculum.get("generation", "?"))
        stats = curriculum.get("stats", {})
        preds = stats.get("predecessors_analyzed", 0)
        rate = stats.get("avg_success_rate", 0)
        lines.append(f"## DOMAIN CURRICULUM: {curriculum.get('domain', '?').title()} (Generation {gen})")
        if preds:
            lines.append(f"  > {preds} predecessors | avg success: {rate:.0%}")
        lines.append("### Learning Path (ordered by dependency)")
        for step in curriculum["learning_path"]:
            skill_tag = f"  Skill: {', '.join(step['skills'])}" if step.get("skills") else ""
            lines.append(f"  {step.get('order', '?')}. **{step.get('name', '?')}** — {step.get('reason', '')}")
            if skill_tag:
                lines.append(f"    {skill_tag}")
            if step.get("anti_pattern"):
                lines.append(f"     X Anti-pattern: {step['anti_pattern']}")
        crit = curriculum.get("critical_failures", [])
        if crit:
            lines.append("### Critical Failures (from your predecessors)")
            lines.extend([f"  !  {f}" for f in crit])
        strats = curriculum.get("proven_strategies", [])
        if strats:
            lines.append("### Proven Strategies")
            lines.extend([f"  *  {s}" for s in strats])
        lines.append("")

    golden_paths = brain_data.get("golden_paths", [])
    if golden_paths:
        lines.append("## GOLDEN PATHS (Proven Success Strategies)")
        for gp in golden_paths[:3]:
            conf = gp.get("confidence", 0)
            obs = gp.get("observation_count", 0)
            lines.append(f"  *  [{gp.get('domain', '?')}] {gp.get('title', '?')} ({conf:.0%} conf, {obs} obs)")
            for i, step in enumerate(gp.get("steps", [])[:5], 1):
                lines.append(f"     {i}. {step}")
        lines.append("")

    cross_agent = brain_data.get("cross_agent_intel", [])
    if cross_agent:
        lines.append("## CROSS-AGENT LEARNING (From Other Agents)")
        for ca in cross_agent[:5]:
            lines.append(f"  @  {ca}")
        lines.append("")

    # Phase 5E: Swarm Competence Profile
    competence = brain_data.get("swarm_competence", "")
    if competence:
        lines.append("## SWARM COMPETENCE (Theory of Mind)")
        lines.append(competence)
        lines.append("")

    # Phase 5D: Autonomy Level
    autonomy = brain_data.get("autonomy_level", "")
    if autonomy:
        lines.append(f"## AUTONOMY: {autonomy}")
        lines.append("")

    # Phase 6C: Culture Principles
    culture = brain_data.get("culture_principles", [])
    if culture:
        lines.append("## TEAM CULTURE (Distilled Principles)")
        for p in culture[:5]:
            lines.append(f"  *  {p.get('title', '?')}: {p.get('description', '')[:80]}")
        lines.append("")

    # Phase 6D: Pending Decisions
    pending_decisions = brain_data.get("pending_decisions", [])
    if pending_decisions:
        lines.append("## PENDING DECISIONS (Submit Your Position)")
        for d in pending_decisions[:3]:
            lines.append(f"  ?  [{d.get('decision_type', '?')}] {d.get('title', '?')} ({len(d.get('positions', []))} votes)")
        lines.append("")

    # Phase 5B: Pending Intentions
    intentions = brain_data.get("pending_intentions", [])
    if intentions:
        lines.append("## PENDING INTENTIONS (Prospective Memory)")
        for i in intentions[:3]:
            lines.append(f"  ~  {i.get('description', '?')[:80]} [{i.get('type', '?')}]")
        lines.append("")

    lines.append("=" * 60)
    return "\n".join(lines)
