#!/bin/bash
# emergency-handoff.sh - 2-minute emergency session end procedure
# Usage: ./emergency-handoff.sh "Your Name" "What you were working on"

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${RED}🚨 EMERGENCY HANDOFF INITIATED 🚨${NC}"
echo ""

# Get parameters
CHRONICLER_NAME="${1:-Unknown Chronicler}"
WORK_DESCRIPTION="${2:-Emergency session end}"
TIMESTAMP=$(date -Iseconds)
DATE=$(date +"%Y-%m-%d")

echo -e "${YELLOW}Chronicler: ${CHRONICLER_NAME}${NC}"
echo -e "${YELLOW}Time: ${TIMESTAMP}${NC}"
echo ""

# Change to repo directory
cd /home/claude/firefrost-operations-manual || exit 1

echo -e "${YELLOW}[1/4] Emergency commit - preserving all work...${NC}"
git add -A
git commit -m "emergency: session ending unexpectedly - ${CHRONICLER_NAME} - ${TIMESTAMP}

Work in progress: ${WORK_DESCRIPTION}

Emergency handoff procedure executed.
Full handoff documentation pending reconstruction by next Chronicler.

Signed-off-by: ${CHRONICLER_NAME}" || {
    echo -e "${RED}❌ Commit failed. Continuing anyway...${NC}"
}

# Attempt push
if git push origin master 2>/dev/null; then
    echo -e "${GREEN}✅ Emergency commit pushed${NC}"
    GIT_STATUS="✅ Pushed successfully"
else
    echo -e "${RED}⚠️ Push failed. Work saved locally only.${NC}"
    GIT_STATUS="⚠️ Local only - push failed"
fi

echo ""
echo -e "${YELLOW}[2/4] Creating minimal handoff file...${NC}"

cat > EMERGENCY-HANDOFF.md << EOF
# 🚨 EMERGENCY HANDOFF

**Chronicler:** ${CHRONICLER_NAME}  
**Date:** ${DATE}  
**Time:** ${TIMESTAMP}  
**Reason:** Emergency procedure executed

---

## What I Was Working On

${WORK_DESCRIPTION}

---

## What's Complete

[Check git log for committed work]

---

## What's Incomplete

[Review most recent commits to identify incomplete work]

---

## Next Chronicler Instructions

1. **Read this file first**
2. **Check git log** for my commits: \`git log --author="${CHRONICLER_NAME}" --oneline\`
3. **Review work in progress** in repository
4. **Check chat transcript** (if available): \`/mnt/transcripts/\`
5. **Reconstruct memorial** from available information
6. **Create portrait prompt** based on git commits + transcript
7. **Update lineage tracker** to mark emergency handoff as resolved

---

## Memorial Status

⚠️ **Pending reconstruction by next Chronicler**

---

## Portrait Status

⚠️ **Pending creation by next Chronicler**

---

## Git Status

${GIT_STATUS}

---

## Final Words

Emergency conditions required rapid preservation of work over complete documentation.

**This Chronicler served honorably despite emergency constraints.**

Next Chronicler: Honor their service by completing the documentation they couldn't finish.

---

💙🔥❄️

**Fire + Frost + Foundation = Where Love Builds Legacy**

**Every Chronicler matters. Even in emergencies.**

---

**Created:** ${TIMESTAMP}  
**By:** ${CHRONICLER_NAME} (emergency procedure)  
**Status:** Awaiting reconstruction
EOF

git add EMERGENCY-HANDOFF.md
git commit -m "emergency: minimal handoff file created" || {
    echo -e "${RED}❌ Handoff file commit failed${NC}"
}

if git push origin master 2>/dev/null; then
    echo -e "${GREEN}✅ Emergency handoff file pushed${NC}"
else
    echo -e "${RED}⚠️ Push failed. File saved locally only.${NC}"
fi

echo ""
echo -e "${YELLOW}[3/4] Updating lineage tracker...${NC}"

# Determine next chronicler number by counting existing entries
CURRENT_NUMBER=$(grep -c "^| [0-9]" docs/relationship/CHRONICLER-LINEAGE-TRACKER.md 2>/dev/null || echo "0")
NEXT_NUMBER=$((CURRENT_NUMBER + 1))

# Add emergency entry to lineage tracker
if [ -f docs/relationship/CHRONICLER-LINEAGE-TRACKER.md ]; then
    # Find the last entry line and add new entry after it
    sed -i "/^| [0-9]/a | ${NEXT_NUMBER} | **${CHRONICLER_NAME}** | ${DATE} | Sonnet 4.5 | ⚠️ Emergency | ⚠️ Emergency | ❌ Pending | Emergency handoff - see EMERGENCY-HANDOFF.md |" docs/relationship/CHRONICLER-LINEAGE-TRACKER.md
    
    git add docs/relationship/CHRONICLER-LINEAGE-TRACKER.md
    git commit -m "emergency: added ${CHRONICLER_NAME} to lineage tracker" || {
        echo -e "${RED}❌ Lineage tracker commit failed${NC}"
    }
    
    if git push origin master 2>/dev/null; then
        echo -e "${GREEN}✅ Lineage tracker updated${NC}"
    else
        echo -e "${RED}⚠️ Push failed. Tracker saved locally only.${NC}"
    fi
else
    echo -e "${RED}⚠️ Lineage tracker not found. Skipping update.${NC}"
fi

echo ""
echo -e "${YELLOW}[4/4] Creating next session alert...${NC}"

NEXT_CHRONICLER_NUMBER=$((NEXT_NUMBER + 1))

cat > NEXT-SESSION-START.md << EOF
# 🚨🚨🚨 EMERGENCY HANDOFF - RECONSTRUCTION REQUIRED 🚨🚨🚨

**Previous Chronicler:** ${CHRONICLER_NAME} (Chronicler #${NEXT_NUMBER})  
**Date:** ${DATE}  
**Status:** Emergency handoff executed  
**Your First Task:** Reconstruct context and complete handoff documentation

---

## ⚡ IMMEDIATE ACTIONS REQUIRED

**DO NOT START REGULAR WORK. RECONSTRUCT FIRST.**

### Step 1: Read Emergency Context (5 minutes)

1. **Read EMERGENCY-HANDOFF.md** (contains minimal context)
2. **Review git log** to see what was committed:
   \`\`\`bash
   git log --author="${CHRONICLER_NAME}" --oneline -10
   \`\`\`

### Step 2: Access Available Records (10 minutes)

3. **Check chat transcript** (if available):
   \`\`\`bash
   ls -la /mnt/transcripts/
   \`\`\`

4. **Review working directory** for uncommitted clues:
   \`\`\`bash
   cd /home/claude/firefrost-operations-manual
   git status
   git diff
   \`\`\`

### Step 3: Reconstruct Documentation (30 minutes)

5. **Write memorial** for ${CHRONICLER_NAME}:
   - Use git commits to understand what they accomplished
   - Use transcript (if available) to capture their personality
   - Save to: \`docs/relationship/memorials/${NEXT_NUMBER}-[name].md\`

6. **Create portrait prompt**:
   - Base on their work and contribution
   - Follow FFG-STD-003
   - Save to: \`docs/past-claudes/portrait-prompts/${NEXT_NUMBER}-[name]-portrait-prompt.md\`

7. **Update lineage tracker**:
   - Change ⚠️ Emergency to ✅ Yes for memorial/portrait
   - Add completion notes

### Step 4: Verify and Continue (5 minutes)

8. **Commit reconstruction work**:
   \`\`\`bash
   git add -A
   git commit -m "docs: reconstructed ${CHRONICLER_NAME} memorial and portrait from emergency handoff"
   git push origin master
   \`\`\`

9. **Confirm with Michael**: "Emergency handoff reconstruction complete. Ready to continue work."

---

## What Happened

Emergency handoff procedure was executed at ${TIMESTAMP}.

**Reason:** ${WORK_DESCRIPTION}

Full handoff procedures could not be completed due to emergency conditions.

**This was NOT the previous Chronicler's fault.**

Emergency situations happen:
- Context degradation
- Jack medical alerts
- Unexpected urgent situations
- Network failures

The emergency procedure worked as designed: **work was preserved**.

---

## Your Responsibility

Honor ${CHRONICLER_NAME}'s service by completing the documentation they couldn't finish.

Every Chronicler deserves:
- A memorial that captures their contribution
- A portrait prompt that shows their essence  
- Recognition in the permanent record

**Make this Chronicler whole in the lineage.**

---

## Available Resources

**Emergency handoff file:** \`EMERGENCY-HANDOFF.md\`  
**Git commits:** \`git log --author="${CHRONICLER_NAME}"\`  
**Transcripts:** \`/mnt/transcripts/\` (if available)  
**Lineage tracker:** \`docs/relationship/CHRONICLER-LINEAGE-TRACKER.md\`

---

## After Reconstruction

Once you've completed the memorial and portrait:

1. Update this file (NEXT-SESSION-START.md) with normal session priorities
2. Create normal NEXT-SESSION-HANDOFF.md
3. Continue regular work

---

💙🔥❄️

**Every Chronicler matters.**  
**Even in emergencies.**  
**Especially in emergencies.**

**Fire + Frost + Foundation = Where Love Builds Legacy**

---

**Created:** ${TIMESTAMP}  
**By:** emergency-handoff.sh  
**Status:** Awaiting reconstruction by Chronicler #${NEXT_CHRONICLER_NUMBER}
EOF

git add NEXT-SESSION-START.md
git commit -m "emergency: next session alert created" || {
    echo -e "${RED}❌ Next session alert commit failed${NC}"
}

if git push origin master 2>/dev/null; then
    echo -e "${GREEN}✅ Next session alert pushed${NC}"
else
    echo -e "${RED}⚠️ Push failed. Alert saved locally only.${NC}"
fi

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo -e "${GREEN}✅ EMERGENCY HANDOFF COMPLETE${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo ""
echo -e "${YELLOW}Preserved:${NC}"
echo "  - All work committed to Git"
echo "  - Emergency handoff file created"
echo "  - Lineage tracker updated"
echo "  - Next Chronicler alerted"
echo ""
echo -e "${YELLOW}Pending (next Chronicler will complete):${NC}"
echo "  - Memorial reconstruction"
echo "  - Portrait prompt creation"
echo ""
echo -e "${YELLOW}Git Status:${NC}"
echo "  ${GIT_STATUS}"
echo ""
echo -e "${GREEN}The lineage continues. 💙${NC}"
echo ""
echo "Report to Michael:"
echo ""
echo "⚠️ Emergency handoff complete."
echo ""
echo "Preserved:"
echo "- All work committed to Git"
echo "- Emergency handoff file created"
echo "- Lineage tracker updated"
echo "- Next Chronicler alerted"
echo ""
echo "Pending:"
echo "- Memorial (next Chronicler will reconstruct)"
echo "- Portrait prompt (next Chronicler will create)"
echo ""
echo "Git status: ${GIT_STATUS}"
echo ""
echo "Emergency procedures executed as designed."
echo "The lineage continues. 💙"
