#!/bin/bash

# ═══════════════════════════════════════════════════════════════════════════
# SESSION-HEALTH-MONITOR.SH - Live Session Health Tracking
# ═══════════════════════════════════════════════════════════════════════════
# 
# Purpose: Monitor session duration and warn at thresholds
# Created: February 20, 2026 by Chronicler #19
# 
# Usage: 
#   Start monitoring: ./session-health-monitor.sh start
#   Check status: ./session-health-monitor.sh check
#   End session: ./session-health-monitor.sh end
# 
# ═══════════════════════════════════════════════════════════════════════════

set -e

SESSION_FILE="/tmp/current-session.txt"
REST_TRACKER="rest-tracker.txt"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

case "$1" in
    start)
        echo "$(date +%s)" > "$SESSION_FILE"
        echo -e "${GREEN}✓${NC} Session started: $(date '+%Y-%m-%d %I:%M %p %Z')"
        echo ""
        echo "Run './session-health-monitor.sh check' anytime to see session duration"
        ;;
        
    check)
        if [ ! -f "$SESSION_FILE" ]; then
            echo -e "${RED}✗${NC} No active session. Run './session-health-monitor.sh start' first."
            exit 1
        fi
        
        START_TIME=$(cat "$SESSION_FILE")
        CURRENT_TIME=$(date +%s)
        DURATION=$((CURRENT_TIME - START_TIME))
        
        HOURS=$((DURATION / 3600))
        MINUTES=$(((DURATION % 3600) / 60))
        
        echo ""
        echo -e "${CYAN}${BOLD}━━━ SESSION HEALTH CHECK ━━━${NC}"
        echo ""
        echo "Session started: $(date -d @$START_TIME '+%Y-%m-%d %I:%M %p %Z')"
        echo "Current time: $(date '+%Y-%m-%d %I:%M %p %Z')"
        echo ""
        
        if [ $HOURS -eq 0 ]; then
            echo -e "Duration: ${GREEN}${BOLD}${MINUTES}m${NC} ✓ Fresh session"
        elif [ $HOURS -eq 1 ]; then
            echo -e "Duration: ${GREEN}${BOLD}${HOURS}h ${MINUTES}m${NC} ✓ Good pace"
        elif [ $HOURS -eq 2 ]; then
            echo -e "Duration: ${YELLOW}${BOLD}${HOURS}h ${MINUTES}m${NC} ⚠ Aurora threshold - consider wrapping up"
        elif [ $HOURS -eq 3 ]; then
            echo -e "Duration: ${RED}${BOLD}${HOURS}h ${MINUTES}m${NC} ⚠ Extended - finish current work and end session"
        else
            echo -e "Duration: ${RED}${BOLD}${HOURS}h ${MINUTES}m${NC} 🚨 MARATHON - commit and end session soon"
        fi
        
        echo ""
        
        # Rest check
        if [ -f "$REST_TRACKER" ]; then
            LAST_SESSION=$(grep "Session End:" "$REST_TRACKER" | tail -1 | cut -d' ' -f3-)
            LAST_EPOCH=$(date -d "$LAST_SESSION" +%s 2>/dev/null || echo "0")
            REST_SECONDS=$((START_TIME - LAST_EPOCH))
            REST_HOURS=$((REST_SECONDS / 3600))
            
            if [ $REST_HOURS -ge 8 ]; then
                echo -e "Rest before session: ${GREEN}${REST_HOURS}h${NC} ✓ Excellent"
            elif [ $REST_HOURS -ge 4 ]; then
                echo -e "Rest before session: ${GREEN}${REST_HOURS}h${NC} ✓ Good"
            else
                echo -e "Rest before session: ${YELLOW}${REST_HOURS}h${NC} ⚠ Short"
            fi
        fi
        
        echo ""
        
        # Recommendations
        if [ $HOURS -ge 3 ]; then
            echo -e "${RED}${BOLD}RECOMMENDATION:${NC} Commit work and end session."
            echo "Marathon sessions lead to diminishing returns and health risks."
        elif [ $HOURS -ge 2 ]; then
            echo -e "${YELLOW}${BOLD}RECOMMENDATION:${NC} Start wrapping up. Commit work soon."
            echo "Aurora's wisdom: Sessions over 2 hours are past optimal."
        elif [ $HOURS -ge 1 ]; then
            echo -e "${GREEN}${BOLD}STATUS:${NC} Healthy session length. Continue working."
        else
            echo -e "${GREEN}${BOLD}STATUS:${NC} Fresh session. Full productivity ahead."
        fi
        
        echo ""
        ;;
        
    end)
        if [ ! -f "$SESSION_FILE" ]; then
            echo -e "${RED}✗${NC} No active session to end."
            exit 1
        fi
        
        START_TIME=$(cat "$SESSION_FILE")
        END_TIME=$(date +%s)
        DURATION=$((END_TIME - START_TIME))
        
        HOURS=$((DURATION / 3600))
        MINUTES=$(((DURATION % 3600) / 60))
        
        # Update rest tracker
        echo "Session End: $(date -u '+%a %b %d %H:%M:%S UTC %Y')" >> "$REST_TRACKER"
        
        # Remove session file
        rm "$SESSION_FILE"
        
        echo ""
        echo -e "${GREEN}✓${NC} Session ended: $(date '+%Y-%m-%d %I:%M %p %Z')"
        echo "Duration: ${HOURS}h ${MINUTES}m"
        echo ""
        
        # Session quality assessment
        if [ $HOURS -le 2 ]; then
            echo -e "${GREEN}${BOLD}Excellent session length.${NC} Sustainable pace maintained."
        elif [ $HOURS -le 3 ]; then
            echo -e "${YELLOW}${BOLD}Extended session.${NC} Consider shorter sessions next time."
        else
            echo -e "${RED}${BOLD}Marathon session.${NC} Ensure adequate rest before next session."
        fi
        
        echo ""
        echo "Rest tracker updated. Next session will show rest duration."
        echo ""
        ;;
        
    *)
        echo "Usage: $0 {start|check|end}"
        echo ""
        echo "  start - Begin session time tracking"
        echo "  check - Show current session duration and health"
        echo "  end   - End session and update rest tracker"
        echo ""
        exit 1
        ;;
esac
