import * as fs from 'fs';
import * as path from 'path';
import { lakesConfig } from './lakesConfig';
import { calculateLakeMetrics } from './utils/calculations';

interface DataRecord {
  timestamp: string;
  level: number;
  flow: number;
}

const lakes = lakesConfig.map(lake => {
  const [internalId, oid] = lake.id.split('|');
  const DATA_FILE = path.resolve(`public/data/${internalId}.json`);
  
  let currentLevel = 0;
  let currentFlow = 0;
  let sparkline: number[] = Array(12).fill(0);

  let capacity = 0;
  let volume = 0;
  let inflow = 0;

  if (fs.existsSync(DATA_FILE)) {
    try {
      const data: any[] = JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
      if (data.length > 0) {
        // Find latest valid record or just the last record
        const lastValidLevelData = [...data].reverse().find(d => d.level !== null && !isNaN(d.level));
        const lastValidFlowData = [...data].reverse().find(d => d.flow !== null && !isNaN(d.flow) && d.flow >= 0);
        
        currentLevel = lastValidLevelData ? lastValidLevelData.level : 0;
        currentFlow = lastValidFlowData ? lastValidFlowData.flow : 0;

        // Take up to 12 last records for sparkline
        const recentData = data.slice(-12);
        sparkline = recentData.map(d => (d.level === null || isNaN(d.level) ? 0 : d.level));
        
        // Pad with zeros if less than 12
        while (sparkline.length < 12) {
          sparkline.unshift(0);
        }

        const latest = data[data.length - 1];
        if (latest.volume && latest.volume > 0) {
          volume = latest.volume;
        }
        if (latest.inflow !== undefined) {
          inflow = latest.inflow;
        }
      }
    } catch (e) {
      console.error(`Error reading data for ${internalId}`, e);
    }
  }
  
  const metrics = calculateLakeMetrics(currentLevel, volume, lake);

  const cleanText = lake.text.replace(/^VD\s+/, '').replace(/^LG\s+/, '');
  const parts = cleanText.split('-').map(p => p.trim());
  let name = '';
  let river = '';
  if (parts.length > 1) {
    river = parts[parts.length - 1];
    name = parts.slice(0, -1).join(' - ');
  } else {
    name = parts[0];
  }

  return {
    id: lake.id,
    name,
    river,
    priority: lake.priority || false,
    level: currentLevel.toFixed(2),
    capacity: metrics.capacity,
    storageDiff: metrics.storageDiff,
    inflow: inflow.toFixed(1),
    outflow: currentFlow.toFixed(1),
    volume: metrics.volume,
    maxVolume: lake.maxVolume || 0,
    navigationForbidden: lake.navigationForbidden || false,
    lat: lake.coords[0],
    lng: lake.coords[1],
    sparkline,
    type: lake.type || 'lake'
  };
});

const outputPath = path.resolve(process.cwd(), 'public/data/lakes_index.json');
fs.writeFileSync(outputPath, JSON.stringify(lakes, null, 2));
console.log('Real lakes index generated:', lakes.length);
