import { execSync } from 'child_process';

// How many minutes after the 10-minute mark should we run the scraper?
// The basin authority (PVL) generates data at HH:00, HH:10, HH:20... but it takes time to publish.
// 7 minutes (HH:07, HH:17...) is a safe buffer to avoid fetching outdated data.
const offsetMinutes = 7;

console.log(`\n⏱️ HLADINATOR Watcher spuštěn!`);
console.log(`Budu automaticky stahovat nová data vždy v časech končících na ${offsetMinutes} (např. 10:07, 10:17, 10:27...).\nTo zajistí, že má Povodí dostatek času data vygenerovat a nahrát.\n`);

function runUpdate() {
  const now = new Date().toLocaleTimeString('cs-CZ');
  console.log(`[${now}] 🔄 Spouštím npm run data:update...`);
  try {
    execSync('npm run data:update', { stdio: 'inherit' });
    console.log(`[${new Date().toLocaleTimeString('cs-CZ')}] ✅ Úspěšně hotovo.\n`);
  } catch (error: any) {
    console.error(`[${new Date().toLocaleTimeString('cs-CZ')}] ❌ Chyba při aktualizaci:`, error.message);
  }
  scheduleNextRun();
}

function scheduleNextRun() {
  const now = new Date();
  const currentMinute = now.getMinutes();
  
  // Find the next target minute (ending in 5)
  // E.g. if it's 12, next will be 15. If it's 26, next will be 35.
  let nextMinute = Math.floor(currentMinute / 10) * 10 + offsetMinutes;
  if (nextMinute <= currentMinute) {
    nextMinute += 10;
  }
  
  const targetTime = new Date(now);
  if (nextMinute >= 60) {
    targetTime.setHours(targetTime.getHours() + 1);
    targetTime.setMinutes(nextMinute % 60);
  } else {
    targetTime.setMinutes(nextMinute);
  }
  targetTime.setSeconds(0);
  targetTime.setMilliseconds(0);
  
  const waitMs = targetTime.getTime() - now.getTime();
  
  console.log(`[${new Date().toLocaleTimeString('cs-CZ')}] ⏳ Další stahování naplánováno na: ${targetTime.toLocaleTimeString('cs-CZ')} (za ${(waitMs / 60000).toFixed(1)} minut)\n`);
  
  setTimeout(runUpdate, waitMs);
}

// Run update immediately on first launch and then set the timer
runUpdate();
