#!/usr/bin/env node
'use strict';
const path = require('path');
const fs = require('fs');
const brain = require(path.resolve(__dirname, '..', '..', '..', 'brain'));

const _standaloneMode = require.main === module;
if (_standaloneMode) brain.initDb();

async function main() {
  const results = { calendarSync: null, cleanup: null, health: null };

  // 1. Calendar sync — pull upcoming meetings
  try {
    const calendar = require(path.resolve(__dirname, '..', '..', '..', 'listening', 'calendar'));
    const source = calendar.getCalendarSource();
    if (source) {
      results.calendarSync = await calendar.syncUpcomingMeetings(2);
    } else {
      results.calendarSync = { synced: 0, source: 'none' };
    }
  } catch (err) {
    results.calendarSync = { error: err.message };
  }

  // 2. Recording cleanup — remove old recordings from disk
  try {
    const storage = require(path.resolve(__dirname, '..', '..', '..', 'listening', 'storage'));
    const cleaned = storage.cleanupOldRecordings(90);
    results.cleanup = { cleaned };
  } catch (err) {
    results.cleanup = { error: err.message };
  }

  // 3. Health check — verify DB recordings have matching files on disk
  try {
    const db = brain.getDb();
    const storage = require(path.resolve(__dirname, '..', '..', '..', 'listening', 'storage'));

    const recordings = db.prepare(
      "SELECT id, audio_path, status FROM recordings WHERE status IN ('done', 'stopped') AND audio_path IS NOT NULL"
    ).all();

    let orphanedDb = 0;
    let orphanedDisk = 0;

    for (const rec of recordings) {
      if (rec.audio_path && !fs.existsSync(rec.audio_path)) {
        orphanedDb++;
      }
    }

    // Check for directories on disk not in DB
    const recordingsDir = storage.getRecordingsDir();
    if (fs.existsSync(recordingsDir)) {
      const dbIds = new Set(db.prepare('SELECT id FROM recordings').all().map(r => r.id));
      for (const entry of fs.readdirSync(recordingsDir)) {
        if (!dbIds.has(entry)) orphanedDisk++;
      }
    }

    results.health = { totalRecordings: recordings.length, orphanedDb, orphanedDisk };
  } catch (err) {
    results.health = { error: err.message };
  }

  console.log(JSON.stringify(results, null, 2));

  if (_standaloneMode) brain.closeDb();
  return results;
}

if (_standaloneMode) {
  main().catch(err => {
    console.error(err.message);
    process.exit(1);
  });
}

module.exports = main;
