#!/bin/bash
# Tdarr Schedule Manager - Easy configuration and testing tool

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
CONFIG_FILE="${SCRIPT_DIR}/tdarr-schedule.conf"
CRON_SCRIPT="${SCRIPT_DIR}/tdarr-cron-check-configurable.sh"

show_help() {
    cat << EOF
Tdarr Schedule Manager

USAGE:
  $0 <command> [options]

COMMANDS:
  show                  - Show current schedule and status
  edit                  - Open configuration file for editing
  test                  - Test current time against schedule rules
  preset <name>         - Apply a preset schedule
  gaming-only           - Enable gaming detection only (no time limits)
  enable-times          - Re-enable time-based scheduling
  add-time <schedule>   - Add a new time block
  install               - Install/update the cron scheduler
  logs                  - Show recent scheduler logs
  status                - Show Tdarr container status

PRESETS:
  night-only           - Only 10PM-7AM daily
  work-safe            - Weekdays 9AM-5PM + nights
  weekend-heavy        - Weekdays 9AM-5PM + nights + weekend days
  minimal              - Only 2AM-6AM daily (very light usage)
  gaming-only          - No time limits, gaming detection only

TIME FORMAT:
  Examples: "22-07:daily"     (10PM-7AM every day)
           "09-17:1-5"       (9AM-5PM Monday-Friday)
           "14-16:6,7"       (2PM-4PM Saturday,Sunday)

EXAMPLES:
  $0 show                    # Show current configuration
  $0 preset night-only       # Set to nights only
  $0 add-time "08-10:6-7"    # Add weekend mornings
  $0 test                    # Test if current time is allowed
EOF
}

show_current_config() {
    echo "📋 Current Tdarr Schedule Configuration"
    echo "======================================"
    
    if [[ -f "$CONFIG_FILE" ]]; then
        echo "🕐 Allowed Time Blocks:"
        grep -E '^[[:space:]]*"[0-9]' "$CONFIG_FILE" | sed 's/^[[:space:]]*/  /'
        echo
        
        echo "🎮 Gaming Processes:"
        grep -A1 'GAMING_PROCESSES=' "$CONFIG_FILE" | tail -1 | sed 's/^[[:space:]]*/  /'
        
        echo "⚙️  Settings:"
        echo "  GPU Threshold: $(grep 'GPU_THRESHOLD=' "$CONFIG_FILE" | cut -d'=' -f2)"
        echo "  Gaming Only Mode: $(grep 'CHECK_GAMING_ONLY=' "$CONFIG_FILE" | cut -d'=' -f2)"
        echo "  Quiet Mode: $(grep 'QUIET_MODE=' "$CONFIG_FILE" | cut -d'=' -f2)"
    else
        echo "❌ Configuration file not found: $CONFIG_FILE"
        return 1
    fi
}

test_current_time() {
    echo "🧪 Testing Current Time Against Schedule"
    echo "======================================="
    echo "Current Time: $(date '+%A, %B %d at %H:%M')"
    echo "Current Day: $(date +%u) (1=Monday, 7=Sunday)"
    echo
    
    if [[ -x "$CRON_SCRIPT" ]]; then
        # Create a test version that shows the result
        local test_result
        export QUIET_MODE=true
        if source "$CONFIG_FILE" && [[ "$CHECK_GAMING_ONLY" == "true" ]]; then
            echo "✅ ALLOWED - Gaming-only mode is enabled"
        else
            # Test the is_time_allowed function
            bash -c "
                source '$CONFIG_FILE'
                $(declare -f is_time_allowed)
                
                current_hour=\$(date +%H | sed 's/^0//')
                current_day=\$(date +%u)
                
                if is_time_allowed; then
                    echo '✅ ALLOWED - Current time matches configured schedule'
                else
                    echo '❌ NOT ALLOWED - Current time outside configured schedule'
                fi
            " 2>/dev/null || echo "⚠️  Error testing schedule"
        fi
    else
        echo "❌ Scheduler script not found or not executable"
    fi
}

apply_preset() {
    local preset="$1"
    
    case "$preset" in
        "night-only")
            cat > "$CONFIG_FILE" << 'EOF'
# Night-only preset: Tdarr runs 10PM-7AM daily
ALLOWED_TIMES=(
    "22-07:daily"        # 10PM to 7AM every day
)
GAMING_PROCESSES=("steam" "lutris" "heroic" "gamemode" "mangohud" "wine" "bottles")
GPU_THRESHOLD=15
CHECK_GAMING_ONLY=false
CONTAINER_NAME="tdarr-node-gpu-unmapped"
LOG_FILE="/tmp/tdarr-scheduler.log"
STARTUP_DELAY=5
QUIET_MODE=false
EOF
            echo "✅ Applied preset: Night-only (10PM-7AM daily)"
            ;;
        "work-safe")
            cat > "$CONFIG_FILE" << 'EOF'
# Work-safe preset: Nights + work hours on weekdays
ALLOWED_TIMES=(
    "22-07:daily"        # 10PM to 7AM every day
    "09-17:1-5"          # 9AM to 5PM Monday-Friday
)
GAMING_PROCESSES=("steam" "lutris" "heroic" "gamemode" "mangohud" "wine" "bottles")
GPU_THRESHOLD=15
CHECK_GAMING_ONLY=false
CONTAINER_NAME="tdarr-node-gpu-unmapped"
LOG_FILE="/tmp/tdarr-scheduler.log"
STARTUP_DELAY=5
QUIET_MODE=false
EOF
            echo "✅ Applied preset: Work-safe (nights + weekday work hours)"
            ;;
        "weekend-heavy")
            cat > "$CONFIG_FILE" << 'EOF'
# Weekend-heavy preset: Maximum transcoding time
ALLOWED_TIMES=(
    "22-07:daily"        # 10PM to 7AM every day
    "09-17:1-5"          # 9AM to 5PM Monday-Friday
    "08-20:6-7"          # 8AM to 8PM weekends
)
GAMING_PROCESSES=("steam" "lutris" "heroic" "gamemode" "mangohud" "wine" "bottles")
GPU_THRESHOLD=15
CHECK_GAMING_ONLY=false
CONTAINER_NAME="tdarr-node-gpu-unmapped"
LOG_FILE="/tmp/tdarr-scheduler.log"
STARTUP_DELAY=5
QUIET_MODE=false
EOF
            echo "✅ Applied preset: Weekend-heavy (nights + work hours + most of weekend)"
            ;;
        "minimal")
            cat > "$CONFIG_FILE" << 'EOF'
# Minimal preset: Very light usage, deep night hours only
ALLOWED_TIMES=(
    "02-06:daily"        # 2AM to 6AM every day
)
GAMING_PROCESSES=("steam" "lutris" "heroic" "gamemode" "mangohud" "wine" "bottles")
GPU_THRESHOLD=15
CHECK_GAMING_ONLY=false
CONTAINER_NAME="tdarr-node-gpu-unmapped"
LOG_FILE="/tmp/tdarr-scheduler.log"
STARTUP_DELAY=5
QUIET_MODE=false
EOF
            echo "✅ Applied preset: Minimal (2AM-6AM daily only)"
            ;;
        "gaming-only")
            sed -i 's/CHECK_GAMING_ONLY=false/CHECK_GAMING_ONLY=true/' "$CONFIG_FILE"
            echo "✅ Applied preset: Gaming-only mode (no time restrictions)"
            ;;
        *)
            echo "❌ Unknown preset: $preset"
            echo "Available presets: night-only, work-safe, weekend-heavy, minimal, gaming-only"
            return 1
            ;;
    esac
}

show_status() {
    echo "📊 Tdarr System Status"
    echo "====================="
    
    # Container status
    if podman ps --format "{{.Names}}\t{{.Status}}" | grep -q "tdarr-node-gpu-unmapped"; then
        echo "🟢 Tdarr Container: RUNNING"
        podman ps --format "{{.Names}}\t{{.Status}}\t{{.CreatedAt}}" | grep tdarr
    else
        echo "🔴 Tdarr Container: STOPPED"
    fi
    echo
    
    # Cron status
    if crontab -l 2>/dev/null | grep -q "tdarr-cron-check"; then
        echo "🟢 Cron Scheduler: ACTIVE"
        echo "   $(crontab -l | grep tdarr-cron-check)"
    else
        echo "🔴 Cron Scheduler: NOT INSTALLED"
    fi
    echo
    
    # Recent activity
    if [[ -f "/tmp/tdarr-scheduler.log" ]]; then
        echo "📋 Last 3 scheduler events:"
        tail -3 /tmp/tdarr-scheduler.log | sed 's/^/   /'
    fi
}

install_scheduler() {
    echo "🔧 Installing/Updating Configurable Tdarr Scheduler"
    
    # Update crontab to use new script
    (crontab -l 2>/dev/null | grep -v "tdarr-cron-check"; echo "* * * * * $CRON_SCRIPT") | crontab -
    
    echo "✅ Scheduler updated in crontab"
    echo "🔍 Current cron entry:"
    crontab -l | grep tdarr-cron-check
}

case "${1:-help}" in
    "show"|"config")
        show_current_config
        ;;
    "edit")
        ${EDITOR:-nano} "$CONFIG_FILE"
        ;;
    "test")
        test_current_time
        ;;
    "preset")
        if [[ -n "$2" ]]; then
            apply_preset "$2"
        else
            echo "❌ Please specify a preset name"
            echo "Available: night-only, work-safe, weekend-heavy, minimal, gaming-only"
        fi
        ;;
    "gaming-only")
        sed -i 's/CHECK_GAMING_ONLY=false/CHECK_GAMING_ONLY=true/' "$CONFIG_FILE"
        echo "✅ Gaming-only mode enabled (no time restrictions)"
        ;;
    "enable-times")
        sed -i 's/CHECK_GAMING_ONLY=true/CHECK_GAMING_ONLY=false/' "$CONFIG_FILE"
        echo "✅ Time-based scheduling re-enabled"
        ;;
    "install")
        install_scheduler
        ;;
    "status")
        show_status
        ;;
    "logs")
        echo "📋 Recent Tdarr Scheduler Logs:"
        tail -20 /tmp/tdarr-scheduler.log 2>/dev/null || echo "No logs found"
        ;;
    "help"|*)
        show_help
        ;;
esac