/**
 * Auto-Backup Scheduler - Runs as a separate process
 * 
 * Usage: tsx scripts/auto-backup-scheduler.ts
 * 
 * This script runs continuously and creates database backups
 * at intervals specified in db/config/storage-paths.json
 */

import * as schedule from 'node-schedule';
import * as fs from 'fs';
import * as path from 'path';
import { performAutomaticBackup } from '@/lib/backup-actions';
import { readStorageConfig } from '@/lib/backup-config';

const LOG_FILE = path.join(process.cwd(), 'db', 'backups', 'scheduler.log');

function ensureLogDir(): void {
  const logDir = path.dirname(LOG_FILE);
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
  }
}

function log(message: string): void {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] ${message}\n`;
  console.log(logMessage);
  
  ensureLogDir();
  fs.appendFileSync(LOG_FILE, logMessage, 'utf-8');
}

async function scheduleBackup(): Promise<void> {
  try {
    const config = readStorageConfig();
    
    if (!config.autoBackupEnabled) {
      log('Auto-backup is disabled. Waiting for next check...');
      return;
    }

    const interval = config.autoBackupIntervalHours || 3;
    const cronExpression = `0 */${interval} * * *`; // Every N hours at minute 0

    log(`Auto-backup enabled with interval: ${interval} hours (cron: ${cronExpression})`);

    schedule.scheduleJob(cronExpression, async () => {
      try {
        log('Starting automatic backup...');
        const result = await performAutomaticBackup();
        
        if (result.success) {
          log(`✓ Automatic backup completed successfully. BackupId: ${result.backupId}`);
        } else {
          log(`✗ Automatic backup failed: ${result.error}`);
        }
      } catch (error: any) {
        log(`✗ Error during automatic backup: ${error?.message || 'Unknown error'}`);
      }
    });

    log('Scheduler started successfully. Waiting for scheduled backups...');
  } catch (error: any) {
    log(`✗ Failed to start scheduler: ${error?.message || 'Unknown error'}`);
    process.exit(1);
  }
}

// Start the scheduler
(async () => {
  log('=== Auto-Backup Scheduler Started ===');
  log(`PID: ${process.pid}`);
  log(`Node env: ${process.env.NODE_ENV || 'development'}`);
  
  await scheduleBackup();

  // Re-check config every 5 minutes to allow dynamic enable/disable and interval changes
  setInterval(async () => {
    try {
      const config = readStorageConfig();
      log('Configuration check: auto-backup is ' + (config.autoBackupEnabled ? 'enabled' : 'disabled'));
    } catch (error: any) {
      log(`Configuration check error: ${error?.message}`);
    }
  }, 5 * 60 * 1000);

  // Graceful shutdown
  process.on('SIGTERM', () => {
    log('SIGTERM received. Shutting down gracefully...');
    process.exit(0);
  });

  process.on('SIGINT', () => {
    log('SIGINT received. Shutting down gracefully...');
    process.exit(0);
  });
})();
