#!/bin/bash

# Configuration
TARGET_FILE="/home/james/TradingBot25/strategies/strategy_activation_scores.py"
LOG_FILE="optimization_log.md"
BACKUP_DIR="backups_optimization_$(date +%Y%m%d_%H%M%S)"
MAX_ITERATIONS=10
GEMINI_CMD="python3 /home/james/TradingBot25/gemini_wrapper.py"

# Ensure we are in the right directory or file exists
if [ ! -f "$TARGET_FILE" ]; then
    echo "Error: Target file $TARGET_FILE not found."
    exit 1
fi

# Check if the command exists
if ! command -v "$GEMINI_CMD" &> /dev/null; then
    echo "Error: Command '$GEMINI_CMD' not found."
    echo "       If '$GEMINI_CMD' is an alias, run 'type $GEMINI_CMD' in your terminal,"
    echo "       copy the real command, and update the GEMINI_CMD variable in this script."
    exit 1
fi

# Create backup directory and initialize log
mkdir -p "$BACKUP_DIR"
echo "# Optimization Session - $(date)" > "$LOG_FILE"
echo "Target: $TARGET_FILE" >> "$LOG_FILE"
echo "" >> "$LOG_FILE"

echo "Starting optimization loop for $MAX_ITERATIONS iterations..."

for ((i=1; i<=MAX_ITERATIONS; i++)); do
    echo "========================================"
    echo "Iteration $i of $MAX_ITERATIONS"
    
    # 1. Backup the current version
    cp "$TARGET_FILE" "$BACKUP_DIR/strategy_activation_scores_iter${i}.py"
    
    # 2. Read current file content
    CURRENT_CODE=$(cat "$TARGET_FILE")
    
    # 3. Construct the Prompt
    # We ask for ONE improvement at a time to keep the context clear and changes manageable.
    PROMPT="You are a world-class Python Quant Developer. 
    I need you to review and optimize the following trading strategy file: 'strategy_activation_scores.py'.
    
    Your Goal: Make the code more robust, faster (vectorization), or cleaner (PEP8/Refactoring).
    
    Instructions:
    1. Analyze the code below.
    2. Identify the SINGLE most important improvement you can make right now.
    3. Explain the improvement briefly.
    4. Provide the COMPLETE, fully working Python code for the file in a markdown code block.
    5. If the code is already optimal and you have no further meaningful suggestions, reply with exactly: NO_CHANGES_NEEDED
    
    Current Code:
    \`\`\`python
    $CURRENT_CODE
    \`\`\`
    "

    # 4. Call Gemini CLI
    echo "Querying Gemini..."
    # We escape double quotes in the prompt if necessary, but usually bash handles the variable expansion okay inside quotes.
    RESPONSE=$($GEMINI_CMD "$PROMPT")
    RET_CODE=$?

    if [ $RET_CODE -ne 0 ]; then
        echo "Error: Gemini CLI failed with exit code $RET_CODE. Skipping iteration."
        continue
    fi
    
    # 5. Check for Stop Condition
    if echo "$RESPONSE" | grep -q "NO_CHANGES_NEEDED"; then
        echo "Gemini indicates no further changes needed. Optimization complete."
        echo "## Iteration $i: Finished" >> "$LOG_FILE"
        echo "No changes suggested." >> "$LOG_FILE"
        break
    fi
    
    # 6. Log the Response
    echo "## Iteration $i" >> "$LOG_FILE"
    echo "$RESPONSE" >> "$LOG_FILE"
    echo "" >> "$LOG_FILE"
    
    # 7. Extract the Code Block
    # This sed command extracts lines between ```python and ``` (excluding the markers)
    # It assumes the LLM follows instructions and outputs one python block.
    NEW_CODE=$(echo "$RESPONSE" | sed -n '/^```python/,/^```/p' | sed '1d;$d')
    
    if [ -z "$NEW_CODE" ]; then
        echo "Warning: No valid Python code block found in response. Skipping update."
        continue
    fi
    
    # 8. Safety Check: Verify Syntax
    echo "$NEW_CODE" > "${TARGET_FILE}.tmp"
    if python3 -m py_compile "${TARGET_FILE}.tmp" >/dev/null 2>&1; then
        mv "${TARGET_FILE}.tmp" "$TARGET_FILE"
        echo "Success: Changes applied and syntax verified."
    else
        echo "Error: Generated code had syntax errors. Reverting this iteration."
        rm "${TARGET_FILE}.tmp"
        # We don't break here, we try again or you might want to break depending on preference
        break
    fi
    
    # Optional: Sleep briefly to avoid rate limits if necessary
    sleep 2
done

echo "========================================"
echo "Loop finished. Review $LOG_FILE for details."
echo "Backups are stored in $BACKUP_DIR"
