#!/usr/bin/env bash
set -euo pipefail

# ════════════════════════════════════════════════════════════════
# Lucky25 Execution Monitoring Script
# ════════════════════════════════════════════════════════════════
# Runs every 15 minutes to monitor lucky25 test plan execution
# Logs status to /var/log/lucky25-monitoring.log
# ════════════════════════════════════════════════════════════════

LOG_FILE="/var/log/lucky25-monitoring.log"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKEND_DIR="${SCRIPT_DIR}/../learning_ai_invt_trdg/backend"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}

log "════════════════════════════════════════════════════════════════"
log "Starting Lucky25 Execution Monitoring"
log "════════════════════════════════════════════════════════════════"

# Create log file if it doesn't exist
touch "$LOG_FILE"

cd "$BACKEND_DIR"

# Run the status check using node with the compiled JS
node -e "
const { config } = require('./dist/src/config/index.js');
const { MANUAL_ENTRY_CONTAINER, queryDocuments } = require('./dist/src/services/tradingRecordStore.js');

async function main() {
    const query = 'SELECT * FROM c WHERE c.productId = @productId AND c.type = @type ORDER BY c.created_at DESC';
    const rows = await queryDocuments(MANUAL_ENTRY_CONTAINER, query, [
        { name: '@productId', value: config.PRODUCT_ID },
        { name: '@type', value: 'manual_entry' },
    ]);

    const lucky25Plans = rows.filter(row =>
        row.hashtags && Array.isArray(row.hashtags) && row.hashtags.includes('lucky25') && row.active === true
    );

    const byStatus = {};
    for (const plan of lucky25Plans) {
        const status = plan.status || 'unknown';
        byStatus[status] = (byStatus[status] || 0) + 1;
    }

    console.log('Lucky25 Plans Status:');
    console.log('Total: ' + lucky25Plans.length);
    console.log('Status breakdown:');
    for (const [status, count] of Object.entries(byStatus)) {
        console.log('  ' + status + ': ' + count);
    }

    const executedPlans = lucky25Plans.filter(p =>
        p.status !== 'simple_armed_buy' && p.status !== 'deleted'
    );

    console.log('Execution Progress:');
    console.log('Executed: ' + executedPlans.length + '/' + lucky25Plans.length);
    console.log('Rate: ' + ((executedPlans.length / lucky25Plans.length) * 100).toFixed(1) + '%');

    if (executedPlans.length > 0) {
        console.log('Recent executions:');
        const recent = executedPlans.slice(0, 3);
        for (const plan of recent) {
            console.log('  ' + plan.symbol + ' - ' + plan.status + ' - ' + plan.label);
        }
    }
}

main().catch(console.error);
"

log "Monitoring check completed"
log "════════════════════════════════════════════════════════════════"
