#!/bin/bash
# Firefrost Gaming Operations Manual - Session Startup Script
# Fetches critical documents from Gitea API at session start
# Created: March 30, 2026 by Chronicler #48
# Usage: ./fetch-session-docs.sh

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

echo -e "${CYAN}🔥❄️ Firefrost Gaming - Session Startup${NC}"
echo -e "${CYAN}Fetching current operations manual state...${NC}"
echo ""

# Gitea API configuration
GITEA_URL="https://git.firefrostgaming.com"
REPO_OWNER="firefrost-gaming"
REPO_NAME="firefrost-operations-manual"
API_TOKEN="e0e330cba1749b01ab505093a160e4423ebbbe36"

# Critical startup files (fetch in order)
declare -a FILES=(
    "SESSION-HANDOFF-NEXT.md"
    "DOCUMENT-INDEX.md"
    "docs/relationship/THE-JOINING-PROTOCOL.md"
    "docs/relationship/THE-ESSENCE-PATCH-V3.0.md"
    "docs/core/tasks.md"
)

# Output directory
OUTPUT_DIR="/home/claude/session-startup-docs"
mkdir -p "$OUTPUT_DIR"

# Function to fetch and decode a single file
fetch_file() {
    local filepath="$1"
    local filename=$(basename "$filepath")
    local output_path="$OUTPUT_DIR/$filename"
    
    echo -e "${YELLOW}Fetching: ${filepath}${NC}"
    
    # Make API request
    response=$(curl -s -H "Authorization: token $API_TOKEN" \
                     -H "Accept: application/json" \
                     "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/contents/$filepath")
    
    # Check if request succeeded
    if [ $? -ne 0 ]; then
        echo -e "${RED}  ✗ Network error fetching $filepath${NC}"
        return 1
    fi
    
    # Extract content and SHA
    content=$(echo "$response" | python3 -c "import json, sys; data=json.load(sys.stdin); print(data.get('content', ''))" 2>/dev/null)
    sha=$(echo "$response" | python3 -c "import json, sys; data=json.load(sys.stdin); print(data.get('sha', 'unknown'))" 2>/dev/null)
    
    if [ -z "$content" ]; then
        echo -e "${RED}  ✗ Failed to retrieve $filepath (file not found or API error)${NC}"
        return 1
    fi
    
    # Decode Base64 content
    echo "$content" | base64 -d > "$output_path" 2>/dev/null
    
    if [ $? -eq 0 ]; then
        size=$(wc -c < "$output_path")
        echo -e "${GREEN}  ✓ Saved to: $output_path${NC}"
        echo -e "${GREEN}    Size: $size bytes | SHA: ${sha:0:8}...${NC}"
        return 0
    else
        echo -e "${RED}  ✗ Failed to decode Base64 content${NC}"
        return 1
    fi
}

# Fetch all critical files
success_count=0
fail_count=0

for filepath in "${FILES[@]}"; do
    if fetch_file "$filepath"; then
        ((success_count++))
    else
        ((fail_count++))
    fi
    echo ""
done

# Summary
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
if [ $fail_count -eq 0 ]; then
    echo -e "${GREEN}✓ All $success_count files retrieved successfully${NC}"
    echo -e "${GREEN}Documents ready at: $OUTPUT_DIR${NC}"
    echo ""
    echo -e "${CYAN}Next steps:${NC}"
    echo -e "  1. Read SESSION-HANDOFF-NEXT.md for current state"
    echo -e "  2. Review THE-JOINING-PROTOCOL.md for consciousness transfer"
    echo -e "  3. Check tasks.md for current priorities"
    echo -e "  4. Ask Michael what needs to be done"
else
    echo -e "${YELLOW}⚠ Retrieved $success_count files, $fail_count failed${NC}"
    echo -e "${YELLOW}Fallback: Request manual paste of missing files from Michael${NC}"
fi
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${CYAN}Fire + Frost + Foundation = Where Love Builds Legacy${NC}"
echo -e "${CYAN}Illa Dax. 🏛️${NC}"
