"""Builds the Reflect "journal" payload the Atlas app renders on its home page.

Pure + dependency-free (no livekit / no LLM) so the lightweight web server can
import and serve it on demand from the same volume files the agent writes:
  - therapy_sessions.json  (durable per-session reflections: summary/themes/...)
  - therapy_stats.json     (usage counters: sessions, total_seconds, guided runs)

Returns {log, themes, cards}:
  log    — the usage tab (sessions, minutes, guided runs, topics tracked)
  themes — "what we're working on", aggregated theme counts (most common first)
  cards  — up to 5 reminder/touch-point cards derived from recent sessions
"""

import json
import os
from collections import Counter

# Card accent colours (ramp names the app maps to its palette).
_PALETTE = ["coral", "green", "amber", "blue", "purple", "pink", "teal"]


def _load_list(path: str) -> list:
    try:
        with open(path) as f:
            data = json.load(f)
        return data if isinstance(data, list) else []
    except Exception:
        return []


def _load_dict(path: str) -> dict:
    try:
        with open(path) as f:
            data = json.load(f)
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def _dedupe(items: list[str]) -> list[str]:
    seen, out = set(), []
    for raw in items:
        s = (raw or "").strip()
        key = s.lower()
        if s and key not in seen:
            seen.add(key)
            out.append(s)
    return out


def _sentence(text: str) -> str:
    """Tidy a fragment into one clean sentence."""
    s = (text or "").strip().rstrip(".").strip()
    if not s:
        return ""
    s = s[0].upper() + s[1:]
    return s + "."


def _first_sentences(text: str, n: int) -> str:
    parts = [p.strip() for p in (text or "").replace("\n", " ").split(".") if p.strip()]
    return ". ".join(parts[:n]) + ("." if parts[:n] else "")


def build_journal(data_dir: str) -> dict:
    sessions = _load_list(os.path.join(data_dir, "therapy_sessions.json"))
    stats = _load_dict(os.path.join(data_dir, "therapy_stats.json"))

    # --- "What we're working on": aggregate themes across all sessions ---
    counts: Counter[str] = Counter()
    display: dict[str, str] = {}
    for s in sessions:
        for t in s.get("themes", []):
            t = (t or "").strip()
            if not t:
                continue
            counts[t.lower()] += 1
            display.setdefault(t.lower(), t)
    themes = [
        {"label": display.get(k, k), "count": c} for k, c in counts.most_common(6)
    ]

    # --- Usage log ---
    log = {
        "sessions": int(stats.get("sessions") or len(sessions)),
        "minutes": round((stats.get("total_seconds") or 0) / 60),
        "guided_runs": int(stats.get("guided_runs") or 0),
        "topics": len(counts),
    }

    # --- Reminder cards from the most recent sessions ---
    recent = list(reversed(sessions[-5:]))  # newest first
    cards: list[dict] = []

    intentions = _dedupe([i for s in recent for i in s.get("open_intentions", [])])
    intent_titles = [
        "Something you said you'd try",
        "A promise to yourself",
        "Worth following up on",
    ]
    for idx, intent in enumerate(intentions[:3]):
        cards.append(
            {
                "tag": "You said you'd try",
                "title": intent_titles[idx % len(intent_titles)],
                "body": _sentence(intent),
                "talk_prompt": f"Let's talk about this: {intent}",
                "icon": "ti-flag",
            }
        )

    if recent:
        summary = (recent[0].get("summary") or "").strip()
        if summary:
            cards.append(
                {
                    "tag": "Last time",
                    "title": "Where we left off",
                    "body": _first_sentences(summary, 2),
                    "talk_prompt": "Continue from where we left off last time.",
                    "icon": "ti-calendar-clock",
                }
            )

    if themes:
        top = themes[0]["label"]
        cards.append(
            {
                "tag": "Worth remembering",
                "title": f"{top} keeps surfacing",
                "body": "It runs under a lot of what you bring — maybe a thread worth pulling.",
                "talk_prompt": f"Let's explore why {top.lower()} keeps coming up for me.",
                "icon": "ti-target-arrow",
            }
        )

    for s in recent:
        helped = (s.get("what_helped") or "").strip()
        if helped:
            cards.append(
                {
                    "tag": "What helped",
                    "title": "This landed for you",
                    "body": _sentence(helped),
                    "talk_prompt": "Can we do more of what's been helping?",
                    "icon": "ti-sparkles",
                }
            )
            break

    cards = cards[:5]
    for i, c in enumerate(cards):
        c["color"] = _PALETTE[i % len(_PALETTE)]

    return {"log": log, "themes": themes, "cards": cards}
