import { CronJob } from 'cron';
import { fetchAllCitiesTemperatures } from './meteoDataHandler';

const MAX_EXECUTION_TIME = 1 * 60 * 60 * 1000; // 1 hour in milliseconds   
const BASE_RETRY_DELAY = 5000; // 5 seconds
const MAX_RETRY_DELAY = 5 * 60 * 1000; // 5 minutes
const MAX_RETRIES = 5;

let jobInProgress = false;
let jobTimeout: NodeJS.Timer;
let retryCount = 0;

const startFetchJob = async (retryDelay = BASE_RETRY_DELAY) => {
    const today = new Date();
    const shortDate = today.toISOString().split('T')[0];
    if (jobInProgress) {
        console.log('Previous job still running, clearing timeout and restarting');
        clearTimeout(jobTimeout);
    }
    
    jobInProgress = true;
    
    // Set timeout to restart job if it stalls
    jobTimeout = setTimeout(() => {
        console.log('Job appears stalled, restarting...');
        jobInProgress = false;
        retryCount = 0; // Reset retry count for stalled jobs
        startFetchJob();
    }, MAX_EXECUTION_TIME);

    try {
        const response = await fetchAllCitiesTemperatures(shortDate);
        if (!response.ok) {
            throw new Error('Temperature fetch job failed');
        }
        retryCount = 0; // Reset retry count on success
    } catch (error) {
        console.error('Error in temperature fetch job:', error);
        
        if (retryCount < MAX_RETRIES) {
            retryCount++;
            const nextDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY);
            console.log(`Retrying in ${nextDelay/1000} seconds (attempt ${retryCount}/${MAX_RETRIES})`);
            
            setTimeout(() => {
                startFetchJob(nextDelay);
            }, retryDelay);
        } else {
            console.error(`Max retries (${MAX_RETRIES}) reached, waiting for next scheduled run`);
            retryCount = 0;
        }
    } finally {
        clearTimeout(jobTimeout);
        jobInProgress = false;
    }
};

const temperatureCronJob = new CronJob('0 0 * * *', () => {
    retryCount = 0; // Reset retry count for new scheduled runs
    startFetchJob();
}, () => {
    console.log('Temperature cron job completed for: ', new Date().toISOString().split('T')[0]);
}, true, 'UTC');

// the date will be saved in string format "YYYY-MM-DD"
export function startTemperatureCronJob() {
    temperatureCronJob.start();
    const today = new Date();
    console.log('Temperature cron job scheduled');
    // Run immediately on startup if no data exists for today
    if (today.getUTCHours() > 0) { // Only run if it's past midnight UTC
        startFetchJob();
    }
}