import axios from 'axios';
import * as cheerio from 'cheerio';
import fs from 'fs';
import https from 'https';

async function compare() {
  const URL = 'https://www.pvl.cz/portal/nadrze/cz/pc/Mereni.aspx?oid=1&id=VLL1';
  const agent = new https.Agent({ rejectUnauthorized: false });
  const response = await axios.get(URL, { httpsAgent: agent });
  const $ = cheerio.load(response.data);
  
  let tblFound = null;
  $('table').each((i, tbl) => {
    if ($(tbl).text().includes('Datum') && $(tbl).text().includes('Odtok')) {
      tblFound = $(tbl);
    }
  });

  const pvlRows = [];
  if (tblFound) {
    tblFound.find('tr').each((i, row) => {
      if (i === 0) return;
      const cols = $(row).find('td');
      if (cols.length >= 3) {
        const rawDate = $(cols[0]).text().trim(); 
        const levelStr = $(cols[1]).text().trim().replace(',', '.');
        let flowStr = $(cols[2]).text().trim().replace(',', '.');
        if (flowStr === '' && cols.length >= 4) {
          flowStr = $(cols[3]).text().trim().replace(',', '.');
        }
        pvlRows.push({
          date: rawDate,
          level: parseFloat(levelStr),
          flow: parseFloat(flowStr)
        });
      }
    });
  }

  const localData = JSON.parse(fs.readFileSync('public/data/VLL1.json', 'utf-8'));
  // Sort local data descending (newest first) to match PVL which is newest first
  const sortedLocal = localData.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

  console.log('--- POROVNÁNÍ DAT: LIPNO 1 ---');
  console.log(String('PVL.CZ').padEnd(40) + ' | ' + 'NAŠE LOKÁLNÍ DATABÁZE');
  console.log('-'.repeat(85));
  
  for (let i = 0; i < Math.min(10, pvlRows.length); i++) {
    const p = pvlRows[i];
    const l = sortedLocal[i];
    
    // Format our local UTC timestamp back to something readable
    const d = new Date(l.timestamp);
    const localDateStr = `${d.getDate().toString().padStart(2, '0')}.${(d.getMonth()+1).toString().padStart(2, '0')}.${d.getFullYear()} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
    
    const pvlStr = `[${p.date}] H: ${p.level} m, O: ${p.flow} m3/s`.padEnd(40);
    const locStr = `[${localDateStr}] H: ${l.level} m, O: ${l.flow} m3/s, P: ${l.inflow} m3/s`;
    
    console.log(`${pvlStr} | ${locStr}`);
  }
}

compare().catch(console.error);
