/**
 * Demo Alert Generator
 * 
 * Generates fake sensor alerts for demonstration purposes.
 * Run with: npx ts-node src/scripts/demo-alerts.ts
 */

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const DEMO_SENSORS = [
    { id: 'demo-pulse-1', name: 'Flower Room - Pulse Pro', roomId: 'flower-room' },
    { id: 'demo-pulse-2', name: 'Veg Room - Pulse', roomId: 'veg-room' },
];

const ALERT_TYPES = [
    { type: 'TEMPERATURE_HIGH', metric: 'temperature', min: 82, max: 88 },
    { type: 'TEMPERATURE_LOW', metric: 'temperature', min: 58, max: 64 },
    { type: 'HUMIDITY_HIGH', metric: 'humidity', min: 72, max: 78 },
    { type: 'HUMIDITY_LOW', metric: 'humidity', min: 35, max: 42 },
    { type: 'VPD_HIGH', metric: 'vpd', min: 1.5, max: 1.8 },
];

async function generateDemoAlert() {
    const sensor = DEMO_SENSORS[Math.floor(Math.random() * DEMO_SENSORS.length)];
    const alertConfig = ALERT_TYPES[Math.floor(Math.random() * ALERT_TYPES.length)];

    const value = alertConfig.min + Math.random() * (alertConfig.max - alertConfig.min);
    const threshold = alertConfig.type.includes('HIGH')
        ? value - 5
        : value + 5;

    const alert = await prisma.environmentAlert.create({
        data: {
            type: alertConfig.type,
            severity: 'WARNING',
            message: `${sensor.name}: ${alertConfig.metric} ${alertConfig.type.includes('HIGH') ? 'above' : 'below'} threshold (${value.toFixed(1)} vs ${threshold.toFixed(1)})`,
            value: value,
            threshold: threshold
        }
    });

    console.log(`🚨 Generated alert: ${alert.message}`);
    return alert;
}

async function generateDemoReading() {
    const sensor = DEMO_SENSORS[Math.floor(Math.random() * DEMO_SENSORS.length)];

    // Generate realistic readings
    const temperature = 72 + (Math.random() - 0.5) * 10; // 67-77°F
    const humidity = 55 + (Math.random() - 0.5) * 15;    // 47-62%
    const vpd = 1.0 + (Math.random() - 0.5) * 0.4;       // 0.8-1.2 kPa

    const reading = await prisma.sensorReading.create({
        data: {
            sensorId: sensor.id,
            value: temperature,
            unit: '°F',
            timestamp: new Date()
        }
    });

    console.log(`📊 Generated reading: ${sensor.name} - ${temperature.toFixed(1)}°F, ${humidity.toFixed(1)}% RH`);
    return reading;
}

async function runDemoMode(intervalMs: number = 5000, alertChance: number = 0.2) {
    console.log('🎭 Demo mode started');
    console.log(`   Interval: ${intervalMs}ms`);
    console.log(`   Alert chance: ${alertChance * 100}%`);
    console.log('   Press Ctrl+C to stop\n');

    const loop = async () => {
        await generateDemoReading();

        if (Math.random() < alertChance) {
            await generateDemoAlert();
        }
    };

    // Initial run
    await loop();

    // Repeat
    setInterval(loop, intervalMs);
}

// CLI interface
const args = process.argv.slice(2);
const command = args[0] || 'run';

if (command === 'alert') {
    generateDemoAlert().then(() => process.exit(0));
} else if (command === 'reading') {
    generateDemoReading().then(() => process.exit(0));
} else if (command === 'run') {
    const interval = parseInt(args[1] || '5000');
    const alertChance = parseFloat(args[2] || '0.2');
    runDemoMode(interval, alertChance);
} else {
    console.log(`
Usage:
  npx ts-node src/scripts/demo-alerts.ts alert     - Generate single alert
  npx ts-node src/scripts/demo-alerts.ts reading   - Generate single reading
  npx ts-node src/scripts/demo-alerts.ts run [interval] [alertChance]
                                                   - Run continuous demo mode
                                                   - interval: ms between readings (default: 5000)
                                                   - alertChance: 0-1 probability (default: 0.2)
`);
}
