#!/bin/bash

# ─────────────────────────────────────────
# puthayal_runner.sh - Runs puthayal.py every 15 seconds with logging
# Similar to cleanUp.sh structure
# ─────────────────────────────────────────

# Configuration
PYTHON_SCRIPT="/var/www/html/python/puthayal.py"
LOG_DIR="/var/www/html/logs"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
LOG_FILE="$LOG_DIR/puthayal_${TIMESTAMP}.log"
CURRENT_LINK="$LOG_DIR/puthayal_current.log"
LOCK_FILE="/tmp/puthayal_runner.lock"
MAX_LOG_FILES=3  # Number of log files to keep (adjust as needed)
RUN_INTERVAL=29    # Run every 29 seconds

# ─────────────────────────────────────────
# SETUP - Create directories
# ─────────────────────────────────────────
mkdir -p "$LOG_DIR"

# Function to log with timestamp
log() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local message="[$timestamp] $1"
    echo "$message"
}

# Function to clean up old log files (keep only last MAX_LOG_FILES runs)
cleanup_old_logs() {
    log "--- CLEANING UP OLD LOG FILES ---"
    log "Maximum log files to keep: $MAX_LOG_FILES"
    
    # Count log files
    local log_files=$(ls -1 "$LOG_DIR"/puthayal_*.log 2>/dev/null | grep -v "puthayal_current.log" | wc -l)
    log "Total log files found: $log_files"
    
    # Keep only last MAX_LOG_FILES log files (delete oldest ones)
    if [ "$log_files" -gt "$MAX_LOG_FILES" ]; then
        local files_to_delete=$((log_files - MAX_LOG_FILES))
        log "Keeping only $MAX_LOG_FILES most recent log files. Removing $files_to_delete oldest file(s)..."
        
        # List files by modification time (oldest first) and delete excess
        ls -t "$LOG_DIR"/puthayal_*.log 2>/dev/null | grep -v "puthayal_current.log" | tail -n "$files_to_delete" | while IFS= read -r old_log; do
            if [ -f "$old_log" ] && [ ! -L "$old_log" ]; then
                log "  Removing old log file: $(basename "$old_log")"
                rm -f "$old_log"
            fi
        done
        
        # Verify cleanup
        local remaining_files=$(ls -1 "$LOG_DIR"/puthayal_*.log 2>/dev/null | grep -v "puthayal_current.log" | wc -l)
        log "Cleanup complete. $remaining_files log files remaining."
    else
        log "Log file count ($log_files) is within limit ($MAX_LOG_FILES). No files to delete."
    fi
}

# Function to run the Python script once with logging
run_python_script() {
    local run_timestamp=$(date '+%Y%m%d_%H%M%S')
    local run_log="$LOG_DIR/puthayal_${run_timestamp}.log"
    
    log "🚀 Starting puthayal.py execution at $(date '+%Y-%m-%d %H:%M:%S')"
    
    for sym in nifty sensex; do
        {
            echo "============================================"
            echo "puthayal.py EXECUTION STARTED at $(date '+%Y-%m-%d %H:%M:%S')"
            echo "Command: /usr/bin/python3 $PYTHON_SCRIPT $sym 1"
            echo "============================================"

            #/usr/bin/python3 "$PYTHON_SCRIPT" "$sym" 1 2>&1    #create entries
            /usr/bin/python3 "$PYTHON_SCRIPT" "$sym" 2>&1
            local exit_code=$?

            echo "============================================"
            echo "puthayal.py EXECUTION FINISHED at $(date '+%Y-%m-%d %H:%M:%S')"
            echo "Exit code: $exit_code"
            echo "============================================"
        } >> "$run_log" 2>&1
    done

    # Run moneyHeistClients.py for DB account
    #{
    #    sleep 1
    #    echo "============================================"
    #    echo "moneyHeistClients.py EXECUTION STARTED at $(date '+%Y-%m-%d %H:%M:%S')"
    #    echo "Command: /usr/bin/python3 /var/www/html/python/moneyHeistClients.py DB"
    #    echo "============================================"
    #
    #    /usr/bin/python3 /var/www/html/python/moneyHeistClients.py DB 2>&1
    #    local exit_code=$?

    #    echo "============================================"
    #    echo "moneyHeistClients.py EXECUTION FINISHED at $(date '+%Y-%m-%d %H:%M:%S')"
    #    echo "Exit code: $exit_code"
    #    echo "============================================"
    #} >> "$run_log" 2>&1

    
    # Update symlink to point to latest log
    if [ -L "$CURRENT_LINK" ]; then
        rm -f "$CURRENT_LINK"
    fi
    ln -s "$run_log" "$CURRENT_LINK"
    
    log "✅ Execution complete. Log saved to: $run_log"
    log "   Symlink: $CURRENT_LINK -> $run_log"
    
    # Show last few lines of output
    echo ""
    echo "📊 Last 5 lines of output:"
    tail -5 "$run_log" | sed 's/^/   /'
    echo ""
    
    return $exit_code
}

# ─────────────────────────────────────────
# MAIN LOOP
# ─────────────────────────────────────────
main() {
    echo "============================================"
    log "puthayal RUNNER STARTED"
    log "PID: $$"
    log "Configuration:"
    log "  - Python script: $PYTHON_SCRIPT"
    log "  - Parameters: 0 1 true disable_opposite"
    log "  - Run interval: $RUN_INTERVAL seconds"
    log "  - Log directory: $LOG_DIR"
    log "  - Max log files: $MAX_LOG_FILES"
    echo "============================================"
    echo ""

    # Create lock file to prevent multiple runners
    if [ -f "$LOCK_FILE" ]; then
        local old_pid=$(cat "$LOCK_FILE" 2>/dev/null)
        if kill -0 "$old_pid" 2>/dev/null; then
            log "❌ ERROR: Another runner is already running with PID $old_pid"
            log "   Lock file: $LOCK_FILE"
            log "   Exiting..."
            exit 1
        else
            log "⚠️  Found stale lock file. Removing..."
            rm -f "$LOCK_FILE"
        fi
    fi
    
    # Create new lock file with current PID
    echo $$ > "$LOCK_FILE"
    log "🔒 Lock file created: $LOCK_FILE (PID: $$)"
    
    # Clean up old logs on startup
    cleanup_old_logs
    echo ""

    # Main execution loop
    local iteration=1
    while true; do
        echo "--------------------------------------------"
        log "🔄 Iteration #$iteration at $(date '+%Y-%m-%d %H:%M:%S')"
        echo "--------------------------------------------"
        
        # Run the Python script
        run_python_script
        
        # Check exit code
        local exit_code=$?
        if [ $exit_code -ne 0 ]; then
            log "⚠️  Python script exited with code: $exit_code"
        fi
        
        echo ""
        log "⏱️  Waiting $RUN_INTERVAL seconds until next run..."
        echo ""
        
        # Wait for the specified interval
        sleep "$RUN_INTERVAL"
        
        iteration=$((iteration + 1))
        
        # Clean up old logs periodically (every 10 iterations)
        if [ $((iteration % 2)) -eq 0 ]; then
            cleanup_old_logs
        fi
    done
}

# ─────────────────────────────────────────
# CLEANUP FUNCTION (on script exit)
# ─────────────────────────────────────────
cleanup() {
    log ""
    log "🛑 Shutting down puthayal runner (PID: $$)..."
    
    # Remove lock file
    if [ -f "$LOCK_FILE" ] && [ "$(cat "$LOCK_FILE" 2>/dev/null)" = "$$" ]; then
        rm -f "$LOCK_FILE"
        log "🔓 Lock file removed: $LOCK_FILE"
    fi
    
    log "👋 Goodbye!"
    exit 0
}

# Set up trap to catch interrupts
trap cleanup SIGINT SIGTERM

# Run main function
main