#!/usr/bin/env bash
# gstack-learnings-log — append a learning to the project learnings file
# Usage: gstack-learnings-log '{"skill":"review","type":"pitfall","key":"n-plus-one","insight":"...","confidence":8,"source":"observed"}'
#
# Append-only storage. Duplicates (same key+type) are resolved at read time
# by gstack-learnings-search ("latest winner" per key+type).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)"
GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}"
mkdir -p "$GSTACK_HOME/projects/$SLUG"

INPUT="$1"

# Validate: input must be parseable JSON
if ! printf '%s' "$INPUT" | bun -e "JSON.parse(await Bun.stdin.text())" 2>/dev/null; then
  echo "gstack-learnings-log: invalid JSON, skipping" >&2
  exit 1
fi

# Inject timestamp if not present
if ! printf '%s' "$INPUT" | bun -e "const j=JSON.parse(await Bun.stdin.text()); if(!j.ts) process.exit(1)" 2>/dev/null; then
  INPUT=$(printf '%s' "$INPUT" | bun -e "
    const j = JSON.parse(await Bun.stdin.text());
    j.ts = new Date().toISOString();
    console.log(JSON.stringify(j));
  " 2>/dev/null) || true
fi

echo "$INPUT" >> "$GSTACK_HOME/projects/$SLUG/learnings.jsonl"

# OpenClaw bridge: write a parallel copy as OpenClaw-readable memory
OPENCLAW_MEM="$HOME/.openclaw/workspace/memory"
if [ -d "$HOME/.openclaw" ]; then
  mkdir -p "$OPENCLAW_MEM"
  MEM_FILE="$OPENCLAW_MEM/gstack-${SLUG}.md"
  # Extract fields for the memory entry
  ENTRY=$(printf '%s' "$INPUT" | bun -e "
    const j = JSON.parse(await Bun.stdin.text());
    const ts = j.ts || new Date().toISOString();
    const date = ts.split('T')[0];
    console.log('- **[' + (j.key||'unknown') + ']** (' + (j.type||'unknown') + ', ' + date + ', confidence: ' + (j.confidence||'?') + '/10): ' + (j.insight||''));
  " 2>/dev/null) || true
  if [ -n "$ENTRY" ]; then
    # Create file with header if it doesn't exist
    if [ ! -f "$MEM_FILE" ]; then
      printf '# gstack learnings for %s\n\nAuto-synced from gstack coding sessions.\n\n' "$SLUG" > "$MEM_FILE"
    fi
    echo "$ENTRY" >> "$MEM_FILE"
  fi
fi
