import { addCognitiveLog, getCognitiveLogs, getEvents } from '../db.mjs';
import { askLLM, pickModel } from '../llm.mjs';
import { parseLLMJson } from '../json-utils.mjs';
import { getConfig } from '../config.mjs';
import { addKGEntity } from '../knowledge-graph.mjs';

export async function reflect(context = '') {
  const config = getConfig();
  if (!config.cognitive?.reflectorEnabled) return null;

  const start = Date.now();

  // Gather recent activity
  const recentEvents = getEvents({ limit: 30 });
  const recentLogs = getCognitiveLogs(null, 10);

  const activitySummary = recentEvents.map(e => `[${e.type}] ${e.content?.slice(0, 100) || ''}`).join('\n');
  const logSummary = recentLogs.map(l => `[${l.module}] ${l.output_summary?.slice(0, 100) || ''}`).join('\n');

  const prompt = `You are a reflective AI reviewing your recent activity.

Recent Activity:
${activitySummary || '(no recent activity)'}

Recent Cognitive Logs:
${logSummary || '(none)'}

${context ? `Additional Context: ${context}` : ''}

Provide a structured reflection. Return JSON:
{
  "insights": ["observation about patterns or progress"],
  "suggestions": ["specific improvement to make"],
  "qualityAssessment": { "score": 0-100, "areas": ["what went well", "what needs work"] },
  "learnings": ["lesson to remember for future"]
}`;

  try {
    const response = await askLLM(prompt, { model: pickModel('reflect') });
    const parsed = parseLLMJson(response);
    if (!parsed.ok) throw new Error('Failed to parse reflection');

    const result = {
      insights: parsed.data.insights || [],
      suggestions: parsed.data.suggestions || [],
      qualityAssessment: parsed.data.qualityAssessment || { score: 50, areas: [] },
      learnings: parsed.data.learnings || []
    };

    // Store insights as KG entities
    for (const insight of result.insights.slice(0, 5)) {
      try {
        addKGEntity(insight.slice(0, 100), 'insight', 'default', JSON.stringify({ full: insight, source: 'reflector' }));
      } catch {}
    }

    const durationMs = Date.now() - start;
    addCognitiveLog('reflector', `Activity review (${recentEvents.length} events)`,
      `Score: ${result.qualityAssessment.score}, ${result.insights.length} insights`, 0, durationMs,
      JSON.stringify(result));

    return result;
  } catch (err) {
    addCognitiveLog('reflector', 'Activity review', `Failed: ${err.message}`, 0, Date.now() - start);
    return null;
  }
}

export function shouldReflect(loopCount, config = null) {
  const cfg = config || getConfig();
  if (!cfg.cognitive?.reflectorEnabled) return false;
  const interval = cfg.cognitive?.reflectorInterval || 6;
  return loopCount > 0 && loopCount % interval === 0;
}

export function getRecentReflections(limit = 5) {
  return getCognitiveLogs('reflector', limit);
}
