#!/bin/bash

# Trip With Us Advanced Session Management Script
# Version 2.0 - Enhanced with comprehensive validation and monitoring

set -e  # Exit on any error

# Configuration
PROJECT_NAME="Trip With Us"
DEV_PORT=8080
SUPABASE_PORT=54321
MIN_NODE_VERSION="18.0.0"
MIN_COVERAGE_THRESHOLD=80
MAX_BUILD_TIME=120  # seconds

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

# Logging functions
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

log_section() {
    echo -e "\n${BLUE}=== $1 ===${NC}"
}

# Utility functions
check_command() {
    if command -v "$1" >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

check_port() {
    local port=$1
    if lsof -i:$port >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

get_git_status() {
    if [ -d ".git" ]; then
        echo "$(git status --porcelain | wc -l) files changed"
    else
        echo "Not a git repository"
    fi
}

# Session state management
update_session_state() {
    local action=$1
    local status=$2
    local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    
    # Create state directory if it doesn't exist
    mkdir -p state
    
    # Update project state
    if [ -f "state/project-state.json" ]; then
        # Use jq to update project state if available
        if check_command jq; then
            jq --arg action "$action" --arg status "$status" --arg time "$timestamp" \
               '.last_session = {action: $action, status: $status, timestamp: $time}' \
               state/project-state.json > state/project-state.json.tmp
            mv state/project-state.json.tmp state/project-state.json
        fi
    fi
    
    # Log to session history
    echo "$timestamp,$action,$status" >> state/session-history.log
}

# Main functions
session_start() {
    log_section "$PROJECT_NAME Development Session Start"
    
    # Record session start
    update_session_state "start" "initiated"
    
    # Environment validation
    log_info "Validating development environment..."
    
    # Check Node.js version
    if check_command node; then
        local node_version=$(node --version | sed 's/v//')
        log_success "Node.js: $node_version"
        
        # Version comparison (simplified)
        if [[ "$node_version" < "$MIN_NODE_VERSION" ]]; then
            log_warning "Node.js version may be outdated. Recommended: $MIN_NODE_VERSION+"
        fi
    else
        log_error "Node.js not found"
        exit 1
    fi
    
    # Check npm/yarn
    if check_command npm; then
        log_success "npm: $(npm --version)"
    else
        log_error "npm not found"
        exit 1
    fi
    
    # Check project dependencies
    if [ -f "../package.json" ]; then
        log_success "package.json found"
        
        if [ -d "../node_modules" ]; then
            log_success "node_modules: Present"
        else
            log_warning "node_modules not found. Run 'npm install'"
        fi
    else
        log_error "package.json not found. Are you in the project root?"
        exit 1
    fi
    
    # Supabase validation
    log_info "Checking Supabase status..."
    if check_command supabase; then
        log_success "Supabase CLI: $(supabase --version | head -1)"
        
        if pgrep -f "supabase" > /dev/null; then
            log_success "Supabase: Running"
            
            # Check if Supabase is accessible
            if curl -s "http://localhost:$SUPABASE_PORT/health" >/dev/null 2>&1; then
                log_success "Supabase API: Accessible on port $SUPABASE_PORT"
            else
                log_warning "Supabase API not responding on port $SUPABASE_PORT"
            fi
        else
            log_error "Supabase: Not running"
            log_info "Start with: supabase start"
            exit 1
        fi
    else
        log_error "Supabase CLI not found"
        exit 1
    fi
    
    # Development server check
    log_info "Checking development server..."
    if check_port $DEV_PORT; then
        log_success "Dev Server: Running on port $DEV_PORT"
    else
        log_warning "Dev Server: Not running on port $DEV_PORT"
        log_info "Start with: npm run dev"
    fi
    
    # Git status validation
    log_info "Checking Git status..."
    if [ -d "../.git" ]; then
        local branch=$(cd .. && git branch --show-current)
        local status=$(cd .. && get_git_status)
        
        log_success "Git Branch: $branch"
        log_info "Git Status: $status"
        
        # Check for uncommitted changes
        if [ "$(cd .. && git status --porcelain | wc -l)" -gt 0 ]; then
            log_warning "Uncommitted changes detected"
            (cd .. && git status --short)
        else
            log_success "Working directory clean"
        fi
        
        # Check if branch is up to date
        (cd .. && git fetch >/dev/null 2>&1)
        local behind=$(cd .. && git rev-list --count HEAD..@{u} 2>/dev/null || echo "0")
        local ahead=$(cd .. && git rev-list --count @{u}..HEAD 2>/dev/null || echo "0")
        
        if [ "$behind" -gt 0 ]; then
            log_warning "Branch is $behind commits behind remote"
        fi
        
        if [ "$ahead" -gt 0 ]; then
            log_info "Branch is $ahead commits ahead of remote"
        fi
    else
        log_error "Not a Git repository"
        exit 1
    fi
    
    # TypeScript validation
    log_info "Checking TypeScript compilation..."
    if check_command npx; then
        if (cd .. && npx tsc --noEmit --pretty 2>/dev/null); then
            log_success "TypeScript: No compilation errors"
        else
            log_error "TypeScript: Compilation errors found"
            log_info "Run 'npx tsc --noEmit' for details"
        fi
    else
        log_warning "npx not available for TypeScript check"
    fi
    
    # ESLint validation
    log_info "Checking code linting..."
    if [ -f "../.eslintrc.js" ] || [ -f "../.eslintrc.json" ] || [ -f "../eslint.config.js" ]; then
        local lint_warnings=$(cd .. && npx eslint src/ --format=compact 2>/dev/null | grep -c "warning" || echo "0")
        local lint_errors=$(cd .. && npx eslint src/ --format=compact 2>/dev/null | grep -c "error" || echo "0")
        
        if [ "$lint_errors" -eq 0 ]; then
            if [ "$lint_warnings" -eq 0 ]; then
                log_success "ESLint: No issues found"
            else
                log_warning "ESLint: $lint_warnings warnings found"
            fi
        else
            log_error "ESLint: $lint_errors errors, $lint_warnings warnings"
        fi
    else
        log_warning "ESLint configuration not found"
    fi
    
    # Meta-agent configuration validation
    log_info "Checking meta-agent configuration..."
    local config_issues=0
    
    if [ -f "config/agent-persona.md" ]; then
        log_success "Agent persona: Configured"
    else
        log_error "Agent persona: Missing"
        ((config_issues++))
    fi
    
    if [ -f "config/project-config.json" ]; then
        if check_command jq && jq empty config/project-config.json >/dev/null 2>&1; then
            log_success "Project config: Valid JSON"
        else
            log_error "Project config: Invalid JSON"
            ((config_issues++))
        fi
    else
        log_error "Project config: Missing"
        ((config_issues++))
    fi
    
    if [ -f "state/project-state.json" ]; then
        log_success "Project state: Present"
    else
        log_warning "Project state: Missing (will be created)"
    fi
    
    # Performance baseline
    log_info "Establishing performance baseline..."
    local build_start=$(date +%s)
    if (cd .. && timeout $MAX_BUILD_TIME npm run build >/dev/null 2>&1); then
        local build_end=$(date +%s)
        local build_time=$((build_end - build_start))
        log_success "Build time: ${build_time}s"
        
        # Store baseline
        echo "build_time=$build_time" > state/performance-baseline.env
    else
        log_error "Build failed or exceeded ${MAX_BUILD_TIME}s timeout"
    fi
    
    # Session summary
    log_section "Session Start Summary"
    if [ "$config_issues" -eq 0 ]; then
        log_success "✅ All systems ready for development"
        update_session_state "start" "success"
    else
        log_warning "⚠️  $config_issues configuration issues found"
        log_info "Address issues before proceeding with development"
        update_session_state "start" "warning"
    fi
    
    # Generate session context
    cat > state/current-session.json << EOF
{
  "session_id": "$(date +%s)",
  "start_time": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "environment": {
    "node_version": "$(node --version)",
    "git_branch": "$(cd .. && git branch --show-current)",
    "git_status": "$(cd .. && get_git_status)",
    "supabase_running": $(pgrep -f "supabase" > /dev/null && echo "true" || echo "false"),
    "dev_server_running": $(check_port $DEV_PORT && echo "true" || echo "false")
  },
  "quality_baseline": {
    "typescript_errors": 0,
    "eslint_warnings": ${lint_warnings:-0},
    "eslint_errors": ${lint_errors:-0},
    "build_time": ${build_time:-0}
  }
}
EOF
    
    log_info "Ready for meta-agent session..."
    log_info "Next: Use your meta-agent to plan and execute development tasks"
}

session_validate() {
    log_section "$PROJECT_NAME Session Validation"
    
    local validation_start=$(date +%s)
    local total_issues=0
    local validation_results=""
    
    update_session_state "validate" "started"
    
    # Load session baseline
    local baseline_file="state/current-session.json"
    if [ -f "$baseline_file" ]; then
        log_info "Using session baseline from $(jq -r '.start_time' $baseline_file 2>/dev/null || echo 'unknown')"
    else
        log_warning "No session baseline found"
    fi
    
    # TypeScript validation
    log_info "Validating TypeScript compilation..."
    if (cd .. && npx tsc --noEmit 2>/dev/null); then
        log_success "TypeScript: ✅ No compilation errors"
        validation_results="${validation_results}typescript:pass,"
    else
        log_error "TypeScript: ❌ Compilation errors found"
        ((total_issues++))
        validation_results="${validation_results}typescript:fail,"
        
        # Show first few errors
        log_info "First 5 TypeScript errors:"
        (cd .. && npx tsc --noEmit 2>&1 | head -10) | while read line; do
            log_error "  $line"
        done
    fi
    
    # ESLint validation
    log_info "Validating code style and quality..."
    local lint_output=$(cd .. && npx eslint src/ --format=compact 2>&1)
    local lint_exit_code=$?
    
    if [ $lint_exit_code -eq 0 ]; then
        log_success "ESLint: ✅ No issues found"
        validation_results="${validation_results}eslint:pass,"
    else
        local error_count=$(echo "$lint_output" | grep -c "error" || echo "0")
        local warning_count=$(echo "$lint_output" | grep -c "warning" || echo "0")
        
        if [ "$error_count" -gt 0 ]; then
            log_error "ESLint: ❌ $error_count errors, $warning_count warnings"
            ((total_issues++))
            validation_results="${validation_results}eslint:fail,"
        else
            log_warning "ESLint: ⚠️  $warning_count warnings (no errors)"
            validation_results="${validation_results}eslint:warning,"
        fi
        
        # Show summary of issues
        if [ "$error_count" -gt 0 ] || [ "$warning_count" -gt 5 ]; then
            log_info "Lint issues summary:"
            echo "$lint_output" | head -15 | while read line; do
                log_warning "  $line"
            done
        fi
    fi
    
    # Unit test validation
    log_info "Running unit tests..."
    local test_output=$(cd .. && npm run test 2>&1)
    local test_exit_code=$?
    
    if [ $test_exit_code -eq 0 ]; then
        # Extract test results
        local test_count=$(echo "$test_output" | grep -o '[0-9]\+ passing' | grep -o '[0-9]\+' || echo "0")
        local failed_count=$(echo "$test_output" | grep -o '[0-9]\+ failing' | grep -o '[0-9]\+' || echo "0")
        
        if [ "$failed_count" -eq 0 ]; then
            log_success "Unit Tests: ✅ $test_count tests passing"
            validation_results="${validation_results}tests:pass,"
        else
            log_error "Unit Tests: ❌ $failed_count tests failing, $test_count passing"
            ((total_issues++))
            validation_results="${validation_results}tests:fail,"
        fi
    else
        log_error "Unit Tests: ❌ Test execution failed"
        ((total_issues++))
        validation_results="${validation_results}tests:error,"
        
        # Show test failures
        log_info "Test failure details:"
        echo "$test_output" | tail -20 | while read line; do
            log_error "  $line"
        done
    fi
    
    # Test coverage validation
    log_info "Checking test coverage..."
    if (cd .. && npm run test:coverage >/dev/null 2>&1); then
        # Extract coverage percentage (this depends on your test setup)
        local coverage_output=$(cd .. && npm run test:coverage 2>&1)
        local coverage_percent=$(echo "$coverage_output" | grep -o 'All files.*[0-9]\+\.[0-9]\+' | grep -o '[0-9]\+\.[0-9]\+' | head -1 || echo "0")
        
        if [ -n "$coverage_percent" ]; then
            local coverage_int=${coverage_percent%.*}
            if [ "$coverage_int" -ge "$MIN_COVERAGE_THRESHOLD" ]; then
                log_success "Test Coverage: ✅ ${coverage_percent}% (≥${MIN_COVERAGE_THRESHOLD}%)"
                validation_results="${validation_results}coverage:pass,"
            else
                log_warning "Test Coverage: ⚠️  ${coverage_percent}% (<${MIN_COVERAGE_THRESHOLD}%)"
                validation_results="${validation_results}coverage:low,"
            fi
        else
            log_warning "Test Coverage: ⚠️  Could not determine coverage"
            validation_results="${validation_results}coverage:unknown,"
        fi
    else
        log_warning "Test Coverage: ⚠️  Coverage script not available"
        validation_results="${validation_results}coverage:unavailable,"
    fi
    
    # Build validation
    log_info "Validating production build..."
    local build_start=$(date +%s)
    
    if (cd .. && timeout $MAX_BUILD_TIME npm run build >/dev/null 2>&1); then
        local build_end=$(date +%s)
        local build_time=$((build_end - build_start))
        
        # Compare with baseline
        local baseline_build_time=0
        if [ -f "state/performance-baseline.env" ]; then
            source state/performance-baseline.env
            baseline_build_time=${build_time:-0}
        fi
        
        if [ "$build_time" -le $((baseline_build_time + 10)) ]; then
            log_success "Build: ✅ Successful (${build_time}s)"
            validation_results="${validation_results}build:pass,"
        else
            log_warning "Build: ⚠️  Successful but slower (${build_time}s vs ${baseline_build_time}s baseline)"
            validation_results="${validation_results}build:slow,"
        fi
        
        # Check build size
        if [ -d "../dist" ]; then
            local build_size=$(du -sh ../dist 2>/dev/null | cut -f1 || echo "unknown")
            log_info "Build size: $build_size"
        fi
    else
        log_error "Build: ❌ Failed or exceeded ${MAX_BUILD_TIME}s timeout"
        ((total_issues++))
        validation_results="${validation_results}build:fail,"
        
        # Show build errors
        log_info "Build error details:"
        (cd .. && npm run build 2>&1 | tail -10) | while read line; do
            log_error "  $line"
        done
    fi
    
    # Supabase integration validation
    log_info "Validating Supabase integration..."
    if pgrep -f "supabase" > /dev/null; then
        if curl -s "http://localhost:$SUPABASE_PORT/health" >/dev/null 2>&1; then
            log_success "Supabase: ✅ Running and accessible"
            validation_results="${validation_results}supabase:pass,"
            
            # Check for type generation
            if [ -f "../src/types/supabase.ts" ]; then
                local types_age=$(find ../src/types/supabase.ts -mtime +1 2>/dev/null | wc -l)
                if [ "$types_age" -gt 0 ]; then
                    log_warning "Supabase types may be outdated (>1 day old)"
                else
                    log_success "Supabase types: Recent"
                fi
            else
                log_warning "Supabase types file not found"
            fi
        else
            log_error "Supabase: ❌ Running but not accessible"
            ((total_issues++))
            validation_results="${validation_results}supabase:inaccessible,"
        fi
    else
        log_error "Supabase: ❌ Not running"
        ((total_issues++))
        validation_results="${validation_results}supabase:down,"
    fi
    
    # File structure validation
    log_info "Validating project structure..."
    local structure_issues=0
    
    # Check required directories
    local required_dirs=("../src/components" "../src/pages" "../src/hooks" "../src/types")
    for dir in "${required_dirs[@]}"; do
        if [ -d "$dir" ]; then
            log_success "${dir#../}: ✅ Present"
        else
            log_warning "${dir#../}: ⚠️  Missing"
            ((structure_issues++))
        fi
    done
    
    if [ "$structure_issues" -eq 0 ]; then
        validation_results="${validation_results}structure:pass,"
    else
        validation_results="${validation_results}structure:issues,"
    fi
    
    # Security validation
    log_info "Checking security considerations..."
    local security_issues=0
    
    # Check for hardcoded secrets
    if grep -r "SUPABASE_SERVICE_KEY\|OPENAI_API_KEY\|TWILIO_" ../src/ 2>/dev/null | grep -v "process.env" >/dev/null; then
        log_error "Security: ❌ Potential hardcoded secrets found"
        ((security_issues++))
    fi
    
    # Check environment file
    if [ -f "../.env" ]; then
        if [ -f "../.gitignore" ] && grep -q "\.env" ../.gitignore; then
            log_success "Environment: ✅ .env file properly ignored"
        else
            log_warning "Environment: ⚠️  .env file not in .gitignore"
        fi
    else
        log_warning "Environment: ⚠️  No .env file found"
    fi
    
    if [ "$security_issues" -eq 0 ]; then
        validation_results="${validation_results}security:pass,"
    else
        validation_results="${validation_results}security:issues,"
        ((total_issues++))
    fi
    
    # Generate validation report
    local validation_end=$(date +%s)
    local validation_duration=$((validation_end - validation_start))
    
    # Create detailed validation report
    cat > state/validation-report.json << EOF
{
  "validation_id": "$(date +%s)",
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "duration_seconds": $validation_duration,
  "total_issues": $total_issues,
  "results": "$validation_results",
  "status": "$([ $total_issues -eq 0 ] && echo "pass" || echo "fail")",
  "details": {
    "typescript": "$(echo $validation_results | grep -o 'typescript:[^,]*' | cut -d: -f2)",
    "eslint": "$(echo $validation_results | grep -o 'eslint:[^,]*' | cut -d: -f2)",
    "tests": "$(echo $validation_results | grep -o 'tests:[^,]*' | cut -d: -f2)",
    "coverage": "$(echo $validation_results | grep -o 'coverage:[^,]*' | cut -d: -f2)",
    "build": "$(echo $validation_results | grep -o 'build:[^,]*' | cut -d: -f2)",
    "supabase": "$(echo $validation_results | grep -o 'supabase:[^,]*' | cut -d: -f2)",
    "structure": "$(echo $validation_results | grep -o 'structure:[^,]*' | cut -d: -f2)",
    "security": "$(echo $validation_results | grep -o 'security:[^,]*' | cut -d: -f2)"
  }
}
EOF
    
    # Validation summary
    log_section "Validation Summary"
    if [ "$total_issues" -eq 0 ]; then
        log_success "🎉 All validations passed! Code is ready for deployment."
        update_session_state "validate" "success"
    else
        log_error "❌ $total_issues critical issues found that need attention."
        log_info "📋 Review the issues above and fix before proceeding."
        update_session_state "validate" "failed"
    fi
    
    log_info "📊 Validation completed in ${validation_duration}s"
    log_info "📄 Detailed report: state/validation-report.json"
    
    # Provide next steps
    if [ "$total_issues" -eq 0 ]; then
        log_info "✨ Next steps:"
        log_info "  • Commit your changes"
        log_info "  • Create pull request if ready"
        log_info "  • Continue with next development task"
    else
        log_info "🔧 Recommended actions:"
        log_info "  • Fix TypeScript compilation errors first"
        log_info "  • Address ESLint errors (warnings can wait)"
        log_info "  • Ensure all tests are passing"
        log_info "  • Re-run validation after fixes"
    fi
}

session_monitor() {
    log_section "$PROJECT_NAME Session Monitoring"
    
    # Real-time monitoring of development environment
    log_info "Starting continuous monitoring (Ctrl+C to stop)..."
    
    local check_interval=5
    local check_count=0
    
    while true; do
        clear
        echo -e "${BLUE}=== Trip With Us Live Monitor (Check #$((++check_count))) ===${NC}"
        echo "Time: $(date)"
        echo ""
        
        # System status
        echo -e "${BLUE}System Status:${NC}"
        
        # Supabase
        if pgrep -f "supabase" > /dev/null; then
            echo -e "  Supabase: ${GREEN}✅ Running${NC}"
        else
            echo -e "  Supabase: ${RED}❌ Down${NC}"
        fi
        
        # Dev server
        if check_port $DEV_PORT; then
            echo -e "  Dev Server: ${GREEN}✅ Running (port $DEV_PORT)${NC}"
        else
            echo -e "  Dev Server: ${RED}❌ Down${NC}"
        fi
        
        # Git status
        local git_changes=$(cd .. && git status --porcelain | wc -l)
        if [ "$git_changes" -gt 0 ]; then
            echo -e "  Git: ${YELLOW}⚠️  $git_changes files changed${NC}"
        else
            echo -e "  Git: ${GREEN}✅ Clean${NC}"
        fi
        
        # TypeScript compilation (quick check)
        echo ""
        echo -e "${BLUE}Code Quality:${NC}"
        if (cd .. && npx tsc --noEmit >/dev/null 2>&1); then
            echo -e "  TypeScript: ${GREEN}✅ No errors${NC}"
        else
            local ts_errors=$(cd .. && npx tsc --noEmit 2>&1 | grep -c "error TS" || echo "0")
            echo -e "  TypeScript: ${RED}❌ $ts_errors errors${NC}"
        fi
        
        # Memory usage
        echo ""
        echo -e "${BLUE}Resource Usage:${NC}"
        local node_processes=$(pgrep -f "node" | wc -l)
        echo "  Node processes: $node_processes"
        
        # Recent file changes
        echo ""
        echo -e "${BLUE}Recent Changes (last 5 minutes):${NC}"
        find ../src/ -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -type f -mmin -5 2>/dev/null | head -5 | while read file; do
            echo "  📝 ${file#../}"
        done
        
        sleep $check_interval
    done
}

session_cleanup() {
    log_section "$PROJECT_NAME Session Cleanup"
    
    update_session_state "cleanup" "started"
    
    # Clean temporary files
    log_info "Cleaning temporary files..."
    
    # Remove build artifacts if requested
    if [ "$1" = "--full" ]; then
        log_info "Performing full cleanup..."
        
        if [ -d "../dist" ]; then
            rm -rf ../dist
            log_success "Removed dist directory"
        fi
        
        if [ -d "../node_modules/.cache" ]; then
            rm -rf ../node_modules/.cache
            log_success "Cleared node_modules cache"
        fi
    fi
    
    # Clean test coverage reports
    if [ -d "../coverage" ]; then
        rm -rf ../coverage
        log_success "Removed coverage reports"
    fi
    
    # Archive session logs
    local archive_dir="state/archives/$(date +%Y%m%d)"
    mkdir -p "$archive_dir"
    
    if [ -f "state/current-session.json" ]; then
        mv state/current-session.json "$archive_dir/session-$(date +%H%M%S).json"
        log_success "Archived session data"
    fi
    
    # Generate session summary
    log_info "Generating session summary..."
    
    local session_count=$(grep -c "start,success" state/session-history.log 2>/dev/null || echo "0")
    local validation_count=$(grep -c "validate,success" state/session-history.log 2>/dev/null || echo "0")
    
    log_success "Session completed"
    log_info "📊 Session stats:"
    log_info "  • Total sessions: $session_count"
    log_info "  • Successful validations: $validation_count"
    
    update_session_state "cleanup" "completed"
}

# Help function
show_help() {
    cat << EOF
${BLUE}Trip With Us Session Manager${NC}

Usage: $0 [COMMAND] [OPTIONS]

Commands:
  start              Initialize development session
  validate           Run comprehensive validation
  monitor            Real-time environment monitoring
  cleanup [--full]   Clean temporary files and archive session
  help               Show this help message

Options:
  --full             Perform full cleanup (with cleanup command)

Examples:
  $0 start           # Start a new development session
  $0 validate        # Validate current code state
  $0 monitor         # Monitor environment in real-time
  $0 cleanup --full  # Full cleanup and session archive

Environment Variables:
  DEV_PORT          Development server port (default: 8080)
  SUPABASE_PORT     Supabase API port (default: 54321)
  MIN_COVERAGE      Minimum test coverage threshold (default: 80)

Files Created:
  state/current-session.json    Current session data
  state/validation-report.json  Latest validation results
  state/session-history.log     Session history log
  state/performance-baseline.env Performance baseline

For more information, visit the Trip With Us development documentation.
EOF
}

# Main script logic
case "$1" in
    "start")
        session_start
        ;;
    "validate")
        session_validate
        ;;
    "monitor")
        session_monitor
        ;;
    "cleanup")
        session_cleanup "$2"
        ;;
    "help"|"--help"|"-h")
        show_help
        ;;
    *)
        log_error "Unknown command: $1"
        echo ""
        show_help
        exit 1
        ;;
esac