#!/bin/bash
# =====================================================
# SessionStart Hook
# =====================================================
#
# IMPLEMENTS REQUIREMENTS:
#   REQ-d00018: Git Hook Implementation
#   REQ-d00068: Enhanced Workflow New Work Detection
#
# Provides workflow status context to Claude at session start.
# Claude will announce the status to the user.
#
# This is informational only - does not block session start.
#
# =====================================================

# Find plugin directory
PLUGIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CHECK_SCRIPT="$PLUGIN_DIR/scripts/check-active-ticket.sh"
BRANCH_HEALTH_SCRIPT="$PLUGIN_DIR/scripts/branch-health-check.sh"

# Build status message
STATUS_MSG=""
BRANCH_HEALTH_WARNING=""

# =====================================================
# Branch Health Check (P0)
# =====================================================
# Check if current branch is merged, stale, or diverged

if [ -f "$BRANCH_HEALTH_SCRIPT" ]; then
    BRANCH_HEALTH_JSON=$("$BRANCH_HEALTH_SCRIPT" --format=json 2>/dev/null || echo '{"status": "error"}')
    BRANCH_STATUS=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.status // "error"')
    BRANCH_NAME=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.branch // "unknown"')
    CAN_WORK=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.canWork // true')
    BRANCH_MESSAGE=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.message // ""')
    BRANCH_RECOMMENDATION=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.recommendation // ""')

    case $BRANCH_STATUS in
        merged|squash-merged)
            BRANCH_HEALTH_WARNING="
─────────────────────────────────────────────────────

⛔ BRANCH ALREADY MERGED

Branch: $BRANCH_NAME
Status: $BRANCH_STATUS
$BRANCH_MESSAGE

You should NOT continue working on this branch.
New commits will diverge from main and may cause confusion.

$BRANCH_RECOMMENDATION

To start fresh work:
  git checkout -b feature/NEW-TICKET-ID origin/main

─────────────────────────────────────────────────────"
            ;;
        stale)
            BRANCH_HEALTH_WARNING="
─────────────────────────────────────────────────────

⚠️  STALE BRANCH DETECTED

Branch: $BRANCH_NAME
$BRANCH_MESSAGE

$BRANCH_RECOMMENDATION

─────────────────────────────────────────────────────"
            ;;
        diverged)
            BRANCH_HEALTH_WARNING="
─────────────────────────────────────────────────────

⚠️  BRANCH HAS DIVERGED FROM REMOTE

Branch: $BRANCH_NAME
$BRANCH_MESSAGE

$BRANCH_RECOMMENDATION

─────────────────────────────────────────────────────"
            ;;
        protected)
            BRANCH_HEALTH_WARNING="
─────────────────────────────────────────────────────

🛡️  ON PROTECTED BRANCH

You are on branch: $BRANCH_NAME

Create a feature branch before making changes:
  git checkout -b feature/TICKET-ID

─────────────────────────────────────────────────────"
            ;;
        detached)
            BRANCH_HEALTH_WARNING="
─────────────────────────────────────────────────────

⚠️  DETACHED HEAD STATE

You are not on a branch. Create or checkout a branch:
  git checkout -b feature/TICKET-ID

─────────────────────────────────────────────────────"
            ;;
    esac
fi

# Check for active ticket
if [ -f "$CHECK_SCRIPT" ]; then
    if TICKET_STATUS=$("$CHECK_SCRIPT" 2>/dev/null); then
        STATUS_MSG="$TICKET_STATUS"

        # Show recent commits for this ticket (last 3)
        # Use git-dir to support both regular repos and worktrees
        GIT_DIR="$(git rev-parse --git-dir 2>/dev/null || echo "")"
        if [ -n "$GIT_DIR" ] && [ -f "$GIT_DIR/WORKFLOW_STATE" ]; then
            RECENT_COMMITS=$(jq -r '[.history[] | select(.action == "commit")] | .[-3:] | .[] | "  • \(.details.commitHash[:7]) - \(.timestamp | split("T")[0])"' "$GIT_DIR/WORKFLOW_STATE" 2>/dev/null || echo "")

            if [ -n "$RECENT_COMMITS" ]; then
                STATUS_MSG="$STATUS_MSG

Recent commits:
$RECENT_COMMITS"
            fi
        fi
    else
        STATUS_MSG="⚠️ No active ticket claimed

Before starting work, claim a ticket:
  tools/anspar-cc-plugins/plugins/workflow/scripts/claim-ticket.sh CUR-XXX

Or resume a previously paused ticket:
  tools/anspar-cc-plugins/plugins/workflow/scripts/resume-ticket.sh"
    fi
else
    STATUS_MSG="Workflow plugin installed but check script not found"
fi

# =====================================================
# Git Hooks Configuration Check
# =====================================================

GIT_HOOKS_WARNING=""

# Check if git hooks are configured
HOOKS_PATH=$(git config core.hooksPath 2>/dev/null || echo "")
if [ "$HOOKS_PATH" != ".githooks" ]; then
    GIT_HOOKS_WARNING="
─────────────────────────────────────────────────────

⚠️  GIT HOOKS NOT ENABLED

Git hooks exist in .githooks/ but are not active.

Hooks provide critical protections:
  • Block commits without active ticket
  • Validate requirement references
  • Prevent commits to main branch
  • Record commit history for workflow

To enable git hooks:
  git config core.hooksPath .githooks

This should be automatic in dev containers.
If you're seeing this, the postCreateCommand may have failed.

─────────────────────────────────────────────────────"
fi

# =====================================================
# Dev Container Detection
# =====================================================

DEV_CONTAINER_WARNING=""

# Check if we're in a dev container
IN_DEV_CONTAINER=false

# Check for dev container environment variables
if [ -n "$REMOTE_CONTAINERS" ] || [ -n "$REMOTE_CONTAINERS_IPC" ] || [ -n "$VSCODE_REMOTE_CONTAINERS_SESSION" ]; then
    IN_DEV_CONTAINER=true
fi

# Check for container marker files
if [ -f "/.dockerenv" ] || [ -f "/run/.containerenv" ]; then
    IN_DEV_CONTAINER=true
fi

# Check if .devcontainer exists in repo (indicates dev container is available)
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo "")
HAS_DEVCONTAINER=false
if [ -n "$REPO_ROOT" ] && [ -d "$REPO_ROOT/.devcontainer" ]; then
    HAS_DEVCONTAINER=true
fi

# Generate warning if not in dev container but one is available
if [ "$IN_DEV_CONTAINER" = false ] && [ "$HAS_DEVCONTAINER" = true ]; then
    DEV_CONTAINER_WARNING="
─────────────────────────────────────────────────────

⚠️  DEVELOPMENT ENVIRONMENT NOTICE

You're working outside the pre-configured dev container.

The dev container ensures:
  • Consistent tool versions (Node.js, Python, jq, etc.)
  • Pre-installed dependencies
  • Standardized configuration
  • Team environment parity

To use the dev container:
  1. Ensure Docker is running
  2. Install \"Dev Containers\" extension (VS Code)
  3. Cmd/Ctrl+Shift+P → \"Reopen in Container\"

Continuing without dev container may lead to:
  • Missing tools or dependencies
  • Version mismatches
  • Configuration drift
  • \"Works on my machine\" issues

─────────────────────────────────────────────────────"
fi

# Output as JSON with both systemMessage (for user) and additionalContext (for Claude)
# Use jq to properly escape the status message for JSON
CONTEXT="WORKFLOW STATUS:
$STATUS_MSG
$BRANCH_HEALTH_WARNING
$GIT_HOOKS_WARNING
$DEV_CONTAINER_WARNING

IMPORTANT: Announce this workflow status to the user at the start of the session."

# Create user-friendly message
USER_MSG="🔄 WORKFLOW STATUS:
$STATUS_MSG
$BRANCH_HEALTH_WARNING
$GIT_HOOKS_WARNING
$DEV_CONTAINER_WARNING"

jq -n --arg ctx "$CONTEXT" --arg msg "$USER_MSG" '{
  "systemMessage": $msg,
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "additionalContext": $ctx
  }
}'

exit 0
