#!/usr/bin/env bash
# Wayfind — Journal Summary
# Aggregates structured AI session journal entries into weekly digests.
# Surfaces drift patterns, recurring lessons, and per-repo summaries.
#
# Journal entries are generated by Claude Code / Cursor at the end of each
# session in ~/.claude/memory/journal/YYYY-MM-DD.md (or ~/.ai-memory/).
#
# Usage:
#   journal-summary.sh                           # This week (auto-detect dir)
#   journal-summary.sh --last-week               # Last week
#   journal-summary.sh --from 2026-02-01 --to 2026-02-28
#   journal-summary.sh --team ~/team-journals    # Aggregate across team members
#   journal-summary.sh --all --format markdown   # Full history as Markdown
#   journal-summary.sh --dir ~/.ai-memory/memory/journal  # Cursor install path

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────────────

JOURNAL_DIR=""
TEAM_DIR=""
FORMAT="text"
RANGE_MODE="week"
FROM_DATE=""
TO_DATE=""

# ── Helpers ───────────────────────────────────────────────────────────────────

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RESET='\033[0m'
info()  { echo -e "  $1"; }
warn()  { echo -e "${YELLOW}⚠${RESET}  $1" >&2; }

usage() {
    cat <<USAGE
Usage: journal-summary.sh [OPTIONS]

Aggregates AI session journal entries into weekly digests with drift
detection and recurring lesson extraction.

Options:
  --dir <path>        Journal directory (default: auto-detect ~/.claude or ~/.ai-memory)
  --team <path>       Team mode: each subdirectory is a user name containing journal files
  --week              Summarize current week Mon–Sun (default)
  --last-week         Summarize last week Mon–Sun
  --from <YYYY-MM-DD> Start date (inclusive)
  --to   <YYYY-MM-DD> End date (inclusive, default: today)
  --all               Include all available journal files
  --format text       Output as plain text (default)
  --format markdown   Output as Markdown (suitable for Notion, GitHub, Slack)
  --help              Show this message

Examples:
  journal-summary.sh
  journal-summary.sh --last-week
  journal-summary.sh --from 2026-02-01 --to 2026-02-28
  journal-summary.sh --team ~/team-journals --format markdown
  journal-summary.sh --all --format markdown > weekly-report.md

Journal format expected (auto-generated by Wayfind session hooks):
  ## Repo — Session title
  **Why:** Stated goal
  **What:** What was actually done
  **Outcome:** Did we hit the goal?
  **On track?:** Yes / No — reason for drift
  **Lessons:** What to remember next time
USAGE
}

# ── Argument parsing ──────────────────────────────────────────────────────────

while [[ $# -gt 0 ]]; do
    case "$1" in
        --dir)       JOURNAL_DIR="$2"; shift 2 ;;
        --dir=*)     JOURNAL_DIR="${1#--dir=}"; shift ;;
        --team)      TEAM_DIR="$2"; shift 2 ;;
        --team=*)    TEAM_DIR="${1#--team=}"; shift ;;
        --format)    FORMAT="$2"; shift 2 ;;
        --format=*)  FORMAT="${1#--format=}"; shift ;;
        --week)      RANGE_MODE="week"; shift ;;
        --last-week) RANGE_MODE="last-week"; shift ;;
        --all)       RANGE_MODE="all"; shift ;;
        --from)      FROM_DATE="$2"; RANGE_MODE="range"; shift 2 ;;
        --from=*)    FROM_DATE="${1#--from=}"; RANGE_MODE="range"; shift ;;
        --to)        TO_DATE="$2"; shift 2 ;;
        --to=*)      TO_DATE="${1#--to=}"; shift ;;
        --help)      usage; exit 0 ;;
        *)           echo "Unknown option: $1" >&2; usage >&2; exit 1 ;;
    esac
done

if [ "$FORMAT" != "text" ] && [ "$FORMAT" != "markdown" ]; then
    echo "Error: --format must be 'text' or 'markdown'" >&2
    exit 1
fi

# ── Auto-detect journal directory ─────────────────────────────────────────────

if [ -z "$JOURNAL_DIR" ] && [ -z "$TEAM_DIR" ]; then
    if [ -d "$HOME/.claude/memory/journal" ]; then
        JOURNAL_DIR="$HOME/.claude/memory/journal"
    elif [ -d "$HOME/.ai-memory/memory/journal" ]; then
        JOURNAL_DIR="$HOME/.ai-memory/memory/journal"
    else
        echo "Error: no journal directory found." >&2
        echo "Expected: ~/.claude/memory/journal or ~/.ai-memory/memory/journal" >&2
        echo "Specify one with --dir <path> or run: journal-summary.sh --help" >&2
        exit 1
    fi
fi

# ── Date range calculation ────────────────────────────────────────────────────

TODAY=$(date +%Y-%m-%d)

date_offset() {
    # Portable date arithmetic: returns date N days from today
    # Works on macOS (BSD date) and Linux (GNU date)
    local n="$1"
    if date -v "${n}d" +%Y-%m-%d 2>/dev/null; then return; fi
    date -d "${n} days" +%Y-%m-%d 2>/dev/null
}

week_start() {
    # Returns Monday of the week containing the given date (YYYY-MM-DD)
    local d="$1"
    local dow
    if dow=$(date -d "$d" +%u 2>/dev/null); then :; else
        # macOS BSD date
        dow=$(date -j -f "%Y-%m-%d" "$d" +%u 2>/dev/null || echo "1")
    fi
    local offset=$(( -(dow - 1) ))
    if date -d "$d $offset days" +%Y-%m-%d 2>/dev/null; then return; fi
    date -v "${offset}d" -j -f "%Y-%m-%d" "$d" +%Y-%m-%d 2>/dev/null
}

week_end() {
    local start="$1"
    local offset=6
    if date -d "$start $offset days" +%Y-%m-%d 2>/dev/null; then return; fi
    date -v "${offset}d" -j -f "%Y-%m-%d" "$start" +%Y-%m-%d 2>/dev/null
}

case "$RANGE_MODE" in
    week)
        FROM_DATE=$(week_start "$TODAY")
        TO_DATE=$(week_end "$FROM_DATE")
        ;;
    last-week)
        local_start=$(week_start "$TODAY")
        if MON_LAST=$(date -d "$local_start -7 days" +%Y-%m-%d 2>/dev/null); then :; else
            MON_LAST=$(date -v-7d -j -f "%Y-%m-%d" "$local_start" +%Y-%m-%d 2>/dev/null)
        fi
        FROM_DATE="$MON_LAST"
        TO_DATE=$(week_end "$FROM_DATE")
        ;;
    range)
        [ -z "$FROM_DATE" ] && { echo "Error: --from required with --to" >&2; exit 1; }
        [ -z "$TO_DATE" ] && TO_DATE="$TODAY"
        ;;
    all)
        FROM_DATE="0000-01-01"
        TO_DATE="9999-12-31"
        ;;
esac

# ── Collect journal files ─────────────────────────────────────────────────────

collect_files() {
    local dir="$1"
    local user="${2:-}"  # optional user label for team mode
    # Files named YYYY-MM-DD.md within the date range
    while IFS= read -r f; do
        local base
        base=$(basename "$f" .md)
        if [[ "$base" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
            if [[ "$base" > "$FROM_DATE" || "$base" == "$FROM_DATE" ]] && \
               [[ "$base" < "$TO_DATE"   || "$base" == "$TO_DATE"   ]]; then
                echo "$user|$base|$f"
            fi
        fi
    done < <(find "$dir" -maxdepth 1 -name '*.md' 2>/dev/null | sort)
}

FILE_RECORDS=()

if [ -n "$TEAM_DIR" ]; then
    # Team mode: each subdir is a user
    while IFS= read -r subdir; do
        user=$(basename "$subdir")
        journal_subdir=""
        # Accept direct .md files or a journal/ subdir
        if [ -d "$subdir/journal" ]; then
            journal_subdir="$subdir/journal"
        elif [ -d "$subdir" ]; then
            journal_subdir="$subdir"
        fi
        if [ -n "$journal_subdir" ]; then
            while IFS= read -r rec; do
                FILE_RECORDS+=("$rec")
            done < <(collect_files "$journal_subdir" "$user")
        fi
    done < <(find "$TEAM_DIR" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort)
else
    while IFS= read -r rec; do
        FILE_RECORDS+=("$rec")
    done < <(collect_files "$JOURNAL_DIR" "")
fi

if [ ${#FILE_RECORDS[@]} -eq 0 ]; then
    echo "No journal files found for the date range: $FROM_DATE → $TO_DATE"
    echo "Journal directory: ${JOURNAL_DIR:-$TEAM_DIR}"
    exit 0
fi

# ── Python parser and report generator ────────────────────────────────────────

python3 - "$FORMAT" "$FROM_DATE" "$TO_DATE" "${FILE_RECORDS[@]}" <<'PYEOF'
import sys
import re
from collections import defaultdict

format_md = sys.argv[1] == "markdown"
from_date = sys.argv[2]
to_date   = sys.argv[3]
records   = sys.argv[4:]  # "user|date|filepath"


# ── Entry dataclass ────────────────────────────────────────────────────────────

class Entry:
    __slots__ = ['date', 'user', 'repo', 'title',
                 'why', 'what', 'outcome', 'ontrack', 'lessons', 'discovery', 'drifted']
    def __init__(self):
        for s in self.__slots__:
            setattr(self, s, '')
        self.drifted = False


# ── Parser ─────────────────────────────────────────────────────────────────────

FIELD_MAP = {
    '**Why:**':        'why',
    '**What:**':       'what',
    '**Outcome:**':    'outcome',
    '**On track?:**':  'ontrack',
    '**Lessons:**':    'lessons',
    '**Discovery:**':  'discovery',
}

# Sort by longest label first to avoid prefix collisions
FIELD_LABELS = sorted(FIELD_MAP.keys(), key=len, reverse=True)

ENTRY_HEADER = re.compile(r'^## (?!\d{4}-\d{2}-\d{2}|Journal\b)(.+)')
BOLD_LABEL   = re.compile(r'^\*\*[^*]+\*\*:')


def parse_file(path, date, user):
    entries = []
    current = None
    field = None

    try:
        with open(path, encoding='utf-8', errors='replace') as fh:
            for raw in fh:
                line = raw.rstrip('\n\r')

                m = ENTRY_HEADER.match(line)
                if m:
                    if current and current.repo:
                        entries.append(current)
                    current = Entry()
                    current.date = date
                    current.user = user
                    header = m.group(1).strip()
                    # Split on em-dash (—) or en-dash (–) surrounded by spaces
                    for sep in [' \u2014 ', ' \u2013 ', ' - ']:
                        idx = header.find(sep)
                        if idx >= 0:
                            current.repo  = header[:idx].strip()
                            current.title = header[idx + len(sep):].strip()
                            break
                    else:
                        current.repo  = header
                        current.title = ''
                    field = None
                    continue

                if current is None:
                    continue

                # Check for a known field label
                matched = False
                for label in FIELD_LABELS:
                    if line.startswith(label):
                        field = FIELD_MAP[label]
                        val = line[len(label):].lstrip()
                        setattr(current, field, val)
                        matched = True
                        break

                if matched:
                    continue

                # Any other bold heading ends the current field
                if BOLD_LABEL.match(line):
                    field = None
                    continue

                # Continuation line for the current field
                if field and line.strip():
                    existing = getattr(current, field)
                    setattr(current, field,
                            (existing + '\n' + line) if existing else line)

    except (IOError, OSError):
        pass

    if current and current.repo:
        entries.append(current)

    return entries


# ── Drift detection ────────────────────────────────────────────────────────────

DRIFT_RE = re.compile(
    r'\bdrift(?:ed)?\b'
    r'|\boff.track\b'
    r'|\bscope.creep\b'
    r'|\bwent.sideways\b'
    r'|\btangent\b',
    re.IGNORECASE
)
# Negation patterns that cancel a nearby drift signal
NEGATED_DRIFT_RE = re.compile(
    r'\bno\s+drift\b'
    r'|\bzero\s+drift\b'
    r'|\bdid(?:n\'t|n\'t| not)\s+drift\b'
    r'|\bnot\s+drift\b',
    re.IGNORECASE
)
YES_START_RE = re.compile(r'^yes\b', re.IGNORECASE)


def is_drifted(text):
    t = text.strip()
    if not t:
        return False
    # Remove negated drift phrases before checking for drift signals
    cleaned = NEGATED_DRIFT_RE.sub('', t)
    # Starts with "yes" and no remaining drift signal → on track
    if YES_START_RE.match(t) and not DRIFT_RE.search(cleaned):
        return False
    return bool(DRIFT_RE.search(cleaned))


# ── Lesson deduplication ───────────────────────────────────────────────────────

def extract_lesson_bullets(text):
    """Return a list of individual lesson strings (bullet or full text)."""
    bullets = []
    for line in text.splitlines():
        line = line.strip().lstrip('- •').strip()
        if len(line) > 10:
            bullets.append(line)
    return bullets


def find_recurring(all_lesson_lines, min_count=2):
    """Return lesson strings that appear ≥ min_count times (exact match)."""
    counts = defaultdict(int)
    for line in all_lesson_lines:
        counts[line.lower().strip()] += 1
    return [k for k, v in counts.items() if v >= min_count]


# ── Load all entries ───────────────────────────────────────────────────────────

all_entries = []

for rec in records:
    parts = rec.split('|', 2)
    if len(parts) != 3:
        continue
    user, date, path = parts
    entries = parse_file(path, date, user)
    all_entries.extend(entries)

for e in all_entries:
    e.drifted = is_drifted(e.ontrack)

# Sort by date
all_entries.sort(key=lambda e: (e.date, e.user, e.repo))


# ── Output helpers ─────────────────────────────────────────────────────────────

def h1(text):
    if format_md:
        return f'# {text}'
    return f'\n{"="*len(text)}\n{text}\n{"="*len(text)}'

def h2(text):
    if format_md:
        return f'\n## {text}'
    return f'\n{text}\n{"-"*len(text)}'

def h3(text):
    if format_md:
        return f'\n### {text}'
    return f'\n  {text}:'

def bullet(text, indent=0):
    pad = '  ' * indent
    if format_md:
        return f'{pad}- {text}'
    return f'{pad}• {text}'

def divider():
    return ('---' if format_md else '-' * 60)

def bold(text):
    return f'**{text}**' if format_md else text.upper()

def italic(text):
    return f'_{text}_' if format_md else f'({text})'

def truncate(text, max_len=120):
    text = text.replace('\n', ' ').strip()
    return text[:max_len - 3] + '...' if len(text) > max_len else text


# ── Build report ───────────────────────────────────────────────────────────────

lines = []

# Header
range_label = f'{from_date} → {to_date}' if from_date != '0000-01-01' else 'All time'
lines.append(h1(f'AI Session Journal Summary  ·  {range_label}'))

total = len(all_entries)
drifted = [e for e in all_entries if e.drifted]
repos   = sorted(set(e.repo for e in all_entries))
users   = sorted(set(e.user for e in all_entries if e.user))

# Stats line
drift_pct = f'{100 * len(drifted) // total}%' if total else '—'
stats_parts = [
    f'{total} session{"s" if total != 1 else ""}',
    f'{len(repos)} repo{"s" if len(repos) != 1 else ""}',
    f'{len(drifted)} drift{"s" if len(drifted) != 1 else ""} ({drift_pct})',
]
if users:
    stats_parts.insert(1, f'{len(users)} contributor{"s" if len(users) != 1 else ""}')

lines.append('')
lines.append(italic('  '.join(stats_parts)))

# ── Per-contributor section (team mode) ──────────────────────────────────────
if users:
    lines.append(h2('Contributors'))
    for user in users:
        user_entries = [e for e in all_entries if e.user == user]
        user_drifted = [e for e in user_entries if e.drifted]
        user_repos   = sorted(set(e.repo for e in user_entries))
        lines.append(bullet(
            f'{bold(user)} — {len(user_entries)} sessions, '
            f'{len(user_repos)} repos, '
            f'{len(user_drifted)} drift'
        ))

# ── Sessions by repo ─────────────────────────────────────────────────────────
lines.append(h2('Sessions by Repo'))

for repo in repos:
    repo_entries = [e for e in all_entries if e.repo == repo]
    repo_drifted = sum(1 for e in repo_entries if e.drifted)

    drift_note = f'  {italic(f"{repo_drifted} drifted")}' if repo_drifted else ''
    lines.append(h3(f'{repo}{drift_note}'))

    for e in repo_entries:
        prefix = e.date
        if e.user:
            prefix += f' [{e.user}]'
        if e.drifted:
            prefix += ' ⚠'

        title_str = f' — {e.title}' if e.title else ''
        lines.append(bullet(f'{prefix}{title_str}', indent=1))

        if e.why:
            lines.append(bullet(f'{bold("Goal:")} {truncate(e.why)}', indent=2))
        if e.outcome:
            lines.append(bullet(f'{bold("Outcome:")} {truncate(e.outcome)}', indent=2))
        if e.discovery:
            lines.append(bullet(f'{bold("Discovery:")} {truncate(e.discovery)}', indent=2))
        if e.drifted and e.ontrack:
            lines.append(bullet(f'{bold("Drift:")} {truncate(e.ontrack)}', indent=2))

# ── Discovery log (feeds PM and CTO digests) ────────────────────────────────
discoveries = [e for e in all_entries if e.discovery.strip()]
if discoveries:
    lines.append(h2(f'Discoveries  ({len(discoveries)} session{"s" if len(discoveries) != 1 else ""})'))
    lines.append('')
    lines.append('Things learned that challenge assumptions or need PM/CTO attention:')
    lines.append('')
    for e in discoveries:
        who = f' [{e.user}]' if e.user else ''
        title_str = f' — {e.title}' if e.title else ''
        lines.append(bullet(f'{e.date}{who}  {e.repo}{title_str}'))
        lines.append(bullet(f'{truncate(e.discovery, 200)}', indent=1))
else:
    lines.append(h2('Discoveries'))
    lines.append(italic('No discoveries flagged in this period.'))

# ── Drift log ────────────────────────────────────────────────────────────────
if drifted:
    lines.append(h2(f'Drift Log  ({len(drifted)} session{"s" if len(drifted) != 1 else ""})'))
    lines.append('')
    lines.append('Sessions where "On track?" indicated scope creep or goal drift:')
    lines.append('')
    for e in drifted:
        who = f' [{e.user}]' if e.user else ''
        lines.append(bullet(f'{e.date}{who}  {e.repo} — {e.title}'))
        lines.append(bullet(f'{truncate(e.ontrack)}', indent=1))
else:
    lines.append(h2('Drift Log'))
    lines.append(italic('No drift detected in this period.'))

# ── Recurring lessons ────────────────────────────────────────────────────────
all_lesson_lines = []
for e in all_entries:
    if e.lessons:
        all_lesson_lines.extend(extract_lesson_bullets(e.lessons))

recurring = find_recurring(all_lesson_lines, min_count=2)

lines.append(h2('Recurring Lessons'))
if recurring:
    lines.append('')
    lines.append('Lessons that appeared in multiple sessions (worth adding to CLAUDE.md or global-state.md):')
    lines.append('')
    for lesson in sorted(recurring):
        lines.append(bullet(lesson))
else:
    lines.append(italic('No recurring lessons found (each lesson appeared only once).'))

# ── All lessons ──────────────────────────────────────────────────────────────
lines.append(h2('All Lessons'))
seen_lessons = set()
for e in sorted(all_entries, key=lambda x: x.date):
    if not e.lessons:
        continue
    bullets_for_entry = extract_lesson_bullets(e.lessons)
    if not bullets_for_entry:
        continue
    who = f' [{e.user}]' if e.user else ''
    lines.append(h3(f'{e.date}{who}  {e.repo}'))
    for lb in bullets_for_entry:
        key = lb.lower().strip()
        marker = ' ♻' if key in {r.lower() for r in recurring} else ''
        lines.append(bullet(f'{lb}{marker}'))
        seen_lessons.add(key)

if not seen_lessons:
    lines.append(italic('No lessons recorded in this period.'))

# ── Footer ───────────────────────────────────────────────────────────────────
lines.append('')
lines.append(divider())
lines.append(italic('Generated by Wayfind journal-summary.sh'))

print('\n'.join(lines))

PYEOF
