import fs from 'fs';
import path from 'path';
import cron from 'node-cron';
import { toggleCategory } from './policyEngine.js';

const DATA_PATH = '/data/curfew.json';

const DEFAULT_CURFEW = {
  enabled: true,
  blockTime: '21:00',
  unblockTime: '07:00',
  categories: ['Social Media', 'Streaming', 'Gaming'],
  overrideUntil: null,
};

let curfewConfig = {};
let blockJob = null;
let unblockJob = null;

export function loadCurfew() {
  try {
    if (fs.existsSync(DATA_PATH)) {
      const raw = fs.readFileSync(DATA_PATH, 'utf-8');
      curfewConfig = JSON.parse(raw);
      console.log('[Curfew] Loaded curfew config from disk');
    } else {
      curfewConfig = { ...DEFAULT_CURFEW };
      saveCurfew();
      console.log('[Curfew] Created default curfew config');
    }
  } catch (err) {
    console.error('[Curfew] Error loading curfew:', err.message);
    curfewConfig = { ...DEFAULT_CURFEW };
  }
  scheduleCurfew();
}

function saveCurfew() {
  const dir = path.dirname(DATA_PATH);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(DATA_PATH, JSON.stringify(curfewConfig, null, 2));
}

function timeToCron(timeStr) {
  const [hours, minutes] = timeStr.split(':').map(Number);
  return `${minutes} ${hours} * * *`;
}

function scheduleCurfew() {
  if (blockJob) { blockJob.stop(); blockJob = null; }
  if (unblockJob) { unblockJob.stop(); unblockJob = null; }

  if (!curfewConfig.enabled) {
    console.log('[Curfew] Curfew is disabled');
    return;
  }

  const blockCron = timeToCron(curfewConfig.blockTime);
  const unblockCron = timeToCron(curfewConfig.unblockTime);

  blockJob = cron.schedule(blockCron, async () => {
    if (isOverrideActive()) {
      console.log('[Curfew] Override active, skipping block');
      return;
    }
    console.log('[Curfew] Bedtime! Blocking categories...');
    for (const cat of curfewConfig.categories) {
      try {
        await toggleCategory(cat, false);
      } catch (err) {
        console.error(`[Curfew] Failed to block ${cat}:`, err.message);
      }
    }
  });

  unblockJob = cron.schedule(unblockCron, async () => {
    console.log('[Curfew] Good morning! Unblocking categories...');
    curfewConfig.overrideUntil = null;
    saveCurfew();
    for (const cat of curfewConfig.categories) {
      try {
        await toggleCategory(cat, true);
      } catch (err) {
        console.error(`[Curfew] Failed to unblock ${cat}:`, err.message);
      }
    }
  });

  console.log(`[Curfew] Scheduled: block at ${curfewConfig.blockTime}, unblock at ${curfewConfig.unblockTime}`);
}

function isOverrideActive() {
  if (!curfewConfig.overrideUntil) return false;
  if (Date.now() < curfewConfig.overrideUntil) return true;
  curfewConfig.overrideUntil = null;
  saveCurfew();
  return false;
}

export function getCurfew() {
  return {
    ...curfewConfig,
    overrideActive: isOverrideActive(),
  };
}

export function updateCurfew(updates) {
  Object.assign(curfewConfig, updates);
  saveCurfew();
  scheduleCurfew();
  return getCurfew();
}

export function overrideCurfew(minutes) {
  curfewConfig.overrideUntil = Date.now() + minutes * 60 * 1000;
  saveCurfew();
  // Unblock categories during override
  for (const cat of curfewConfig.categories) {
    toggleCategory(cat, true).catch((err) =>
      console.error(`[Curfew] Override unblock failed for ${cat}:`, err.message)
    );
  }
  return getCurfew();
}
