const brain = require('../brain');

async function generateDailySummary(opts = {}) {
  const today = new Date().toISOString().slice(0, 10);

  // Check if summary already exists for today
  const existing = brain.getDailySummary(today);
  if (existing) return existing;

  // Get brain stats
  const stats = brain.getBrainStats();

  // Get recent memories (last 24h, limit 50)
  const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
  const recentMemories = brain.listMemories({ since, limit: 50 });

  let summaryText;
  if (opts.generateFn) {
    summaryText = await opts.generateFn(recentMemories, stats);
  } else {
    // Default summary text (in production this would call an LLM)
    summaryText = `Daily summary for ${today}: ${stats.memory_count} total memories, ${stats.knowledge_count} knowledge entries, ${stats.pending_question_count} pending questions. ${recentMemories.length} memories in last 24h.`;
  }

  const result = brain.insertDailySummary(today, summaryText, stats);
  return { id: result.id, date: today, summary: summaryText, stats: JSON.stringify(stats) };
}

async function runOnce(opts = {}) {
  const { shouldRunLoop, skipped } = require('./loop-precheck');
  const pre = shouldRunLoop({ loopName: 'reflect' });
  if (!pre.run) {
    if (pre.reason === 'no-provider' && !runOnce._pauseLogged) {
      console.log('[reflect] No AI provider available -- pausing');
      runOnce._pauseLogged = true;
    }
    return skipped({ loopName: 'reflect', reason: pre.reason });
  }
  if (runOnce._pauseLogged) {
    console.log('[reflect] Provider available -- resuming');
    runOnce._pauseLogged = false;
  }

  // Get checkpoint
  const checkpoint = brain.getCheckpoint('reflect');
  const lastRunAt = checkpoint ? checkpoint.last_run_at : null;

  // Count new memories since last reflect. Use a DB COUNT — listMemories(...).length
  // pulled every matching row (content blobs and all) just to count them, a full
  // materialization on a 350k-row brain.
  const sinceOpts = lastRunAt ? { since: lastRunAt } : {};
  const memoriesSinceLastReflect = brain.countMemories(sinceOpts);

  // Count pending questions (DB COUNT, not a full materialization)
  const pendingQuestions = brain.countQuestions({ status: 'pending' });

  // Update checkpoint
  brain.upsertCheckpoint('reflect', {
    metadata: JSON.stringify({
      memories_since_last: memoriesSinceLastReflect,
      pending_questions: pendingQuestions,
    }),
  });

  // Run importance decay
  try {
    const decayResult = brain.decayImportance();
    if (decayResult.decayed > 0 || decayResult.boosted > 0) {
      console.log(`[reflect] Importance decay: ${decayResult.decayed} decayed, ${decayResult.boosted} boosted`);
    }
  } catch (err) {
    console.error('[reflect] Importance decay failed:', err.message);
  }

  // Detect stale facts (knowledge with valid_to in past still marked active)
  try {
    const { detectStaleFacts } = require('../extraction/contradiction');
    const stale = detectStaleFacts(20);
    if (stale.length > 0) {
      console.log(`[reflect] Found ${stale.length} stale facts`);
      for (const fact of stale) {
        try { brain.updateKnowledgeStatus(fact.id, 'retracted'); } catch {}
      }
    }
  } catch (err) {
    console.error('[reflect] Stale fact detection failed:', err.message);
  }

  // Update entity confidence based on knowledge references
  try {
    const { updateEntityConfidence } = require('../extraction/entity-normalizer');
    const ecResult = updateEntityConfidence();
    if (ecResult.updated > 0) {
      console.log(`[reflect] Updated confidence for ${ecResult.updated} entities`);
    }
  } catch {}

  // Check if we should generate daily summary
  let summaryGenerated = false;
  const currentHour = new Date().getHours();
  const today = new Date().toISOString().slice(0, 10);
  const existingSummary = brain.getDailySummary(today);

  if (opts.forceSummary || (currentHour >= 23 && !existingSummary)) {
    await generateDailySummary(opts);
    summaryGenerated = true;
  }

  return { memoriesSinceLastReflect, pendingQuestions, summaryGenerated };
}

module.exports = { runOnce, generateDailySummary };
