'use strict';

const brain = require('../brain');
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);

/**
 * Build a compact state snapshot (~500 tokens) of Wall-E's current awareness.
 * Resilient: returns whatever data is available, skips sections that fail.
 */
function buildStateSnapshot() {
  const snapshot = {};
  const db = brain.getDb();

  // 1. Time context
  const now = new Date();
  snapshot.time = {
    datetime: now.toISOString(),
    day_of_week: now.toLocaleDateString('en-US', { weekday: 'long' }),
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    hour: now.getHours(),
  };

  // 2. Calendar: check for cached calendar events in the next 2 hours
  try {
    // Look in briefing_items for calendar-related items
    const calItems = db.prepare(
      "SELECT title, context, urgency FROM briefing_items WHERE (skill = 'google-calendar' OR category = 'calendar') AND status NOT IN ('done', 'dismissed') AND last_seen >= date('now') ORDER BY urgency DESC, last_seen DESC LIMIT 5"
    ).all();
    if (calItems.length > 0) {
      snapshot.calendar = calItems.map(c => ({
        title: c.title,
        context: c.context ? c.context.slice(0, 200) : null,
        urgency: c.urgency,
      }));
    }
  } catch (_) {
    // Calendar data unavailable -- skip
  }

  // 3. Recent memories: last 5 high-importance memories from today
  try {
    const todayStart = now.toISOString().slice(0, 10) + 'T00:00:00.000Z';
    const recentMemories = db.prepare(
      "SELECT id, source, content, importance, timestamp FROM memories WHERE timestamp >= ? ORDER BY importance DESC, timestamp DESC LIMIT 5"
    ).all(todayStart);
    if (recentMemories.length > 0) {
      snapshot.recent_memories = recentMemories.map(m => ({
        id: m.id,
        source: m.source,
        summary: m.content ? m.content.slice(0, 150) : '',
        importance: m.importance,
      }));
    }
  } catch (_) {}

  // 4. Pending tasks: tasks due in next 2 hours
  try {
    const twoHoursFromNow = new Date(now.getTime() + 2 * 60 * 60 * 1000).toISOString();
    const dueTasks = db.prepare(
      "SELECT id, title, priority, due_at FROM tasks WHERE status IN ('pending', 'active') AND due_at IS NOT NULL AND due_at <= ? ORDER BY due_at ASC LIMIT 5"
    ).all(twoHoursFromNow);
    if (dueTasks.length > 0) {
      snapshot.pending_tasks = dueTasks.map(t => ({
        id: t.id,
        title: t.title,
        priority: t.priority,
        due_at: t.due_at,
      }));
    }
  } catch (_) {}

  // 5. Pending questions: unresolved questions (limit 3)
  try {
    const questions = db.prepare(
      "SELECT id, question, priority FROM pending_questions WHERE status = 'pending' ORDER BY CASE WHEN priority = 'high' THEN 0 WHEN priority = 'normal' THEN 1 ELSE 2 END, created_at DESC LIMIT 3"
    ).all();
    if (questions.length > 0) {
      snapshot.pending_questions = questions.map(q => ({
        id: q.id,
        question: q.question.slice(0, 200),
        priority: q.priority,
      }));
    }
  } catch (_) {}

  // 6. Recent decisions: last 5 initiative_log entries (to avoid repeating)
  try {
    const recentDecisions = db.prepare(
      "SELECT decision, decision_data, reasoning, created_at FROM initiative_log ORDER BY created_at DESC LIMIT 5"
    ).all();
    if (recentDecisions.length > 0) {
      snapshot.recent_decisions = recentDecisions.map(d => ({
        decision: d.decision,
        data: d.decision_data ? d.decision_data.slice(0, 200) : null,
        reasoning: d.reasoning ? d.reasoning.slice(0, 150) : null,
        at: d.created_at,
      }));
    }
  } catch (_) {}

  // 7. Knowledge gaps: domains with low confidence (tier 1-2)
  try {
    const gaps = db.prepare(
      "SELECT domain, current_tier, confidence FROM domain_confidence WHERE current_tier <= 2 ORDER BY confidence ASC LIMIT 5"
    ).all();
    if (gaps.length > 0) {
      snapshot.knowledge_gaps = gaps.map(g => ({
        domain: g.domain,
        tier: g.current_tier,
        confidence: g.confidence,
      }));
    }
  } catch (_) {}

  // 8. Briefing items: urgent/today items
  try {
    const briefing = db.prepare(
      "SELECT title, category, urgency, context FROM briefing_items WHERE status NOT IN ('done', 'dismissed') AND (urgency IN ('high', 'critical') OR last_seen >= date('now')) ORDER BY CASE WHEN urgency = 'critical' THEN 0 WHEN urgency = 'high' THEN 1 ELSE 2 END LIMIT 5"
    ).all();
    if (briefing.length > 0) {
      snapshot.briefing_items = briefing.map(b => ({
        title: b.title,
        category: b.category,
        urgency: b.urgency,
      }));
    }
  } catch (_) {}

  return snapshot;
}

/**
 * Check if the snapshot contains no actionable data.
 */
function isStateEmpty(snapshot) {
  const keys = Object.keys(snapshot).filter(k => k !== 'time');
  if (keys.length === 0) return true;
  // Check if all data arrays are empty
  return keys.every(k => {
    const val = snapshot[k];
    return Array.isArray(val) ? val.length === 0 : !val;
  });
}

/**
 * Format the snapshot as human-readable text for the initiative prompt.
 */
function formatSnapshot(snapshot) {
  const lines = [];

  if (snapshot.time) {
    lines.push(`TIME: ${snapshot.time.day_of_week} ${snapshot.time.datetime} (${snapshot.time.timezone})`);
  }

  if (snapshot.calendar && snapshot.calendar.length > 0) {
    lines.push('\nCALENDAR (next 2 hours):');
    for (const c of snapshot.calendar) {
      lines.push(`  - [${c.urgency}] ${c.title}`);
    }
  }

  if (snapshot.recent_memories && snapshot.recent_memories.length > 0) {
    lines.push('\nRECENT MEMORIES (today):');
    for (const m of snapshot.recent_memories) {
      lines.push(`  - [${m.source}, importance=${m.importance}] ${m.summary}`);
    }
  }

  if (snapshot.pending_tasks && snapshot.pending_tasks.length > 0) {
    lines.push('\nPENDING TASKS (due soon):');
    for (const t of snapshot.pending_tasks) {
      lines.push(`  - [${t.priority}] ${t.title} (due: ${t.due_at})`);
    }
  }

  if (snapshot.pending_questions && snapshot.pending_questions.length > 0) {
    lines.push('\nPENDING QUESTIONS:');
    for (const q of snapshot.pending_questions) {
      lines.push(`  - [${q.priority}] ${q.question}`);
    }
  }

  if (snapshot.recent_decisions && snapshot.recent_decisions.length > 0) {
    lines.push('\nRECENT INITIATIVE DECISIONS:');
    for (const d of snapshot.recent_decisions) {
      lines.push(`  - ${d.decision}: ${d.reasoning || '(no reason)'} (${d.at})`);
    }
  }

  if (snapshot.knowledge_gaps && snapshot.knowledge_gaps.length > 0) {
    lines.push('\nKNOWLEDGE GAPS (low confidence):');
    for (const g of snapshot.knowledge_gaps) {
      lines.push(`  - ${g.domain}: tier ${g.tier}, confidence ${g.confidence}`);
    }
  }

  if (snapshot.briefing_items && snapshot.briefing_items.length > 0) {
    lines.push('\nBRIEFING ITEMS (urgent/today):');
    for (const b of snapshot.briefing_items) {
      lines.push(`  - [${b.urgency}] ${b.title} (${b.category || 'general'})`);
    }
  }

  return lines.join('\n');
}

module.exports = { buildStateSnapshot, isStateEmpty, formatSnapshot };
