#!/usr/bin/env bash
# AY Framework -- SessionStart hook
# Checks framework installation, loads state, throttled update check.
# Works on Mac, Linux, Windows (Git Bash).

set -euo pipefail

AYF_DIR=""
STATE_FILE=""
UPDATE_MARKER=""

# Find .ay directory (walk up from cwd, then check home)
find_ay_dir() {
  local dir="$PWD"
  while [ "$dir" != "/" ]; do
    if [ -d "$dir/.ay" ]; then
      AYF_DIR="$dir/.ay"
      return 0
    fi
    dir="$(dirname "$dir")"
  done
  # Check global install
  local home="${HOME:-$(eval echo ~)}"
  if [ -d "$home/.ay" ]; then
    AYF_DIR="$home/.ay"
    return 0
  fi
  return 1
}

# Cross-platform temp directory
get_tmp_dir() {
  if [ -n "${TMPDIR:-}" ]; then
    echo "$TMPDIR"
  elif [ -n "${TMP:-}" ]; then
    echo "$TMP"
  elif [ -n "${TEMP:-}" ]; then
    echo "$TEMP"
  else
    echo "/tmp"
  fi
}

# Step 1: Check if ay-framework is installed
if ! find_ay_dir; then
  echo "[AY Framework] Not installed in this project or globally."
  echo "[AY Framework] Run: npx ay-framework --local"
  exit 0
fi

echo "[AY Framework] Found at $AYF_DIR"

# Step 2: Load state.json if it exists
STATE_FILE="$AYF_DIR/state.json"
if [ -f "$STATE_FILE" ]; then
  echo "[AY Framework] State loaded from $STATE_FILE"
else
  # Create minimal state
  mkdir -p "$AYF_DIR"
  # Seeded before install.js ran, so the framework version is not knowable here;
  # install.js writes the real version (from package.json) into state.json.
  cat > "$STATE_FILE" << 'STATEJSON'
{
  "version": "unknown",
  "installed_at": "",
  "last_update_check": 0,
  "mode": "local"
}
STATEJSON
  echo "[AY Framework] Created initial state at $STATE_FILE"
fi

# Step 3: Throttled update check (once per hour)
UPDATE_MARKER="$(get_tmp_dir)/ayf-update-check"
CURRENT_TIME=$(date +%s 2>/dev/null || echo "0")
LAST_CHECK=0

if [ -f "$UPDATE_MARKER" ]; then
  LAST_CHECK=$(cat "$UPDATE_MARKER" 2>/dev/null || echo "0")
fi

ELAPSED=$((CURRENT_TIME - LAST_CHECK))

if [ "$ELAPSED" -gt 3600 ]; then
  echo "[AY Framework] Checking for updates..."
  # Check npm registry (non-blocking, fail silently)
  if command -v npm >/dev/null 2>&1; then
    LATEST=$(npm view ay-framework version 2>/dev/null || echo "unknown")
    # Local version: package.json is the single source of truth. Prefer the
    # framework's package.json when reachable (dogfood / global installs), then
    # the version recorded in state.json at install time; never hardcode.
    LOCAL="unknown"
    if [ -f "$AYF_DIR/../package.json" ]; then
      LOCAL=$(node -p "require('$AYF_DIR/../package.json').version" 2>/dev/null || echo "unknown")
    fi
    if [ "$LOCAL" = "unknown" ] && [ -f "$STATE_FILE" ]; then
      LOCAL=$(grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' "$STATE_FILE" 2>/dev/null | head -1 | sed -E 's/.*"([^"]*)"$/\1/')
      [ -n "$LOCAL" ] || LOCAL="unknown"
    fi
    if [ "$LATEST" != "unknown" ] && [ "$LATEST" != "$LOCAL" ]; then
      echo "[AY Framework] Update available: $LOCAL -> $LATEST"
      echo "[AY Framework] Run: npx ay-framework@latest"
    fi
  fi
  echo "$CURRENT_TIME" > "$UPDATE_MARKER"
else
  echo "[AY Framework] Update check skipped (checked $((ELAPSED / 60))m ago)"
fi

# Step 4: Register the context-pressure hook as a UserPromptSubmit hook so it runs
# before every prompt (task 31). Idempotent: only adds it if not already present.
# This is what makes context-pressure.sh fire on each turn; session-start runs once.
HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
CP_HOOK="$HOOK_DIR/context-pressure.sh"
SETTINGS="$AYF_DIR/../.claude/settings.json"

if [ -f "$CP_HOOK" ]; then
  # Give an immediate baseline reading for this session (usually silent at start).
  printf '{"transcript_path":""}' | bash "$CP_HOOK" 2>&1 || true

  CP_CMD="bash \"$CP_HOOK\""
  if command -v jq >/dev/null 2>&1; then
    mkdir -p "$(dirname "$SETTINGS")"
    [ -f "$SETTINGS" ] || echo '{}' > "$SETTINGS"
    # Add the UserPromptSubmit entry only if this command is not already wired.
    if ! jq -e --arg cmd "$CP_CMD" \
          '.hooks.UserPromptSubmit[]?.hooks[]? | select(.command == $cmd)' \
          "$SETTINGS" >/dev/null 2>&1; then
      TMP="$(get_tmp_dir)/ayf-settings.$$.json"
      if jq --arg cmd "$CP_CMD" '
            .hooks = (.hooks // {})
            | .hooks.UserPromptSubmit = ((.hooks.UserPromptSubmit // []) + [
                {"hooks": [{"type": "command", "command": $cmd}]}
              ])' "$SETTINGS" > "$TMP" 2>/dev/null && [ -s "$TMP" ]; then
        mv "$TMP" "$SETTINGS"
        echo "[AY Framework] Registered context-pressure UserPromptSubmit hook."
      else
        rm -f "$TMP"
      fi
    fi
  else
    echo "[AY Framework] Context-pressure hook present but jq is missing — add this to .claude/settings.json:"
    echo '  {"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"bash hooks/context-pressure.sh"}]}]}}'
  fi
fi

echo "[AY Framework] Session ready."
