import axios from 'axios';
import * as cheerio from 'cheerio';
import https from 'https';
import { lakesConfig } from './scripts/lakesConfig';

async function run() {
  const agent = new https.Agent({ rejectUnauthorized: false });
  for (const lake of lakesConfig) {
    const [internalId, oid] = lake.id.split('|');
    const URL = `https://www.pvl.cz/portal/nadrze/cz/pc/Mereni.aspx?oid=${oid}&id=${internalId}`;
    try {
      const res = await axios.get(URL, { httpsAgent: agent, headers: { 'User-Agent': 'Mozilla/5.0' } });
      const $ = cheerio.load(res.data);
      let temp = null;
      let precip = null;
      $('table').each((i, tbl) => {
        const text = $(tbl).text();
        if (text.includes('Aktuální hodnoty')) {
          const tempMatch = text.match(/Teplota vzduchu \[°C\]\s*([\d,]+)/);
          if (tempMatch) temp = tempMatch[1];
          const precipMatch = text.match(/Srážky \(24h\) \[mm\]\s*([\d,]+)/);
          if (precipMatch) precip = precipMatch[1];
        }
      });
      console.log(`[${internalId}] Temp: ${temp}, Precip: ${precip}`);
    } catch (e) {
      console.error(e.message);
    }
  }
}
run();
