"""Builds the bootstrapped markdown context string injected at session start.

Tier 0 (identity profile) + Tier 1 (recent session index).
Tier G (global knowledge) will be added in Phase 3.
"""
import logging
from datetime import datetime
from typing import Optional
from bigmind import memory_store

logger = logging.getLogger("BigMindContext")


def _format_date(iso_str: Optional[str]) -> str:
    if not iso_str:
        return "—"
    try:
        dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
        return dt.strftime("%Y-%m-%d")
    except Exception:
        return iso_str[:10]


# Maximum facts loaded into context on session start.
# Keeps context lean as the facts table grows — older/excess facts remain
# searchable via memory_search_facts() but won't bloat every session startup.
_MAX_CONTEXT_FACTS = 50


def build_context(user_id: str, n_sessions: int = 10) -> str:
    """
    Assemble the full bootstrapped context markdown for injection at session start.
    Returns a markdown string (target: ≤ 800 tokens in personal mode).
    """
    lines = [
        f"## 🧠 BigMind Context — loaded {datetime.now().strftime('%Y-%m-%d %H:%M')}",
        "",
    ]

    # ── TIER 0: Identity Profile ──────────────────────────────────────────────
    profile = memory_store.get_identity_profile(user_id)
    if profile:
        lines.append("### 👤 Who you are")
        if profile.get("role"):
            lines.append(f"**Role:** {profile['role']}")
        if profile.get("preferences"):
            lines.append("")
            lines.append("**Preferences:**")
            lines.append(profile["preferences"])
        if profile.get("pinned_facts"):
            lines.append("")
            lines.append("### 📌 Pinned facts")
            for line in profile["pinned_facts"].strip().splitlines():
                lines.append(line if line.startswith("-") else f"- {line}")
    else:
        lines.append("### 👤 Who you are")
        lines.append(
            "*(No profile yet — call `memory_update_profile` to set up your identity)*"
        )

    lines.append("")

    # ── FACTS: Atomic personal facts ─────────────────────────────────────────
    all_facts = memory_store.get_facts(user_id)
    facts = all_facts[:_MAX_CONTEXT_FACTS]
    overflow = len(all_facts) - len(facts)
    if facts:
        lines.append("### 🗂️ Stored facts")
        for f in facts:
            cat = f.get("category", "")
            fact = f.get("fact", "")
            lines.append(f"- **[{cat}]** {fact}")
        if overflow > 0:
            lines.append(
                f"- *… {overflow} more facts available via `memory_search_facts()`*"
            )
        lines.append("")

    # ── TIER 1: Recent Sessions ───────────────────────────────────────────────
    open_sessions = memory_store.get_open_sessions(user_id)
    closed_sessions = memory_store.get_recent_sessions(user_id, limit=n_sessions)

    if open_sessions or closed_sessions:
        lines.append(f"### 📅 Recent sessions (last {len(closed_sessions)} closed)")
        lines.append("| Date | Headline | Topics | Outcome |")
        lines.append("|---|---|---|---|")
        for s in open_sessions:
            date = _format_date(s.get("started_at"))
            sid = (s.get("id") or "")[:8]
            lines.append(f"| {date} | 🟡 **[in progress]** `{sid}…` | — | (session not yet closed) |")
        for s in closed_sessions:
            date = _format_date(s.get("started_at"))
            headline = (s.get("one_liner") or "")[:80]
            topics = (s.get("topics") or "—")[:40]
            outcome = (s.get("outcome") or "—")[:80]
            tier2_hint = " 📄" if s.get("has_tier2") else ""
            lines.append(f"| {date} | {headline}{tier2_hint} | {topics} | {outcome} |")
        lines.append("")
        lines.append(
            "*(📄 = detailed Tier-2 summary available via `memory_get_session_detail`)*"
        )
    else:
        lines.append("### 📅 Recent sessions")
        lines.append(
            "*(No past sessions yet — this is the beginning of your BigMind history)*"
        )

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

