/**
 * Ambient Agent Example
 * Demonstrates how to use the Ambient Agent plugin for autonomous monitoring and actions
 */

const { Framework } = require('../src/core/framework');

async function main() {
  console.log('=== Ambient Agent Example ===\n');

  // Create framework
  const framework = new Framework({
    debug: true,
  });

  // Bootstrap with default plugins (including ambient)
  await framework.bootstrap({
    agentDir: './.agent',
    aiConfig: {
      provider: 'deepseek',
      model: 'deepseek-chat',
      apiKey: process.env.DEEPSEEK_API_KEY || 'your-api-key',
    },
  });

  console.log('\n=== Framework Ready ===\n');

  // Wait for plugins to start
  await new Promise((resolve) => setTimeout(resolve, 1000));

  // Check if ambient plugin is loaded
  const ambientPlugin = framework.pluginManager.get('ambient');
  if (!ambientPlugin) {
    console.error('Ambient plugin not loaded!');
    return;
  }

  console.log('=== Ambient Plugin Tools Available ===');
  const tools = framework.getTools();
  const ambientTools = tools.filter((t) => t.name.startsWith('ambient_'));
  console.log('Ambient tools:', ambientTools.map((t) => t.name).join(', '));

  console.log('\n=== Example 1: Create a Goal ===');
  // Use ambient_goals to create a simple goal
  const createResult = await framework.executeTool('ambient_goals', {
    action: 'create',
    title: 'Monitor System Health',
    description: 'Periodically check system information and alert on issues',
    priority: 8,
    actions: [{ id: 'check_1', type: 'tool', name: 'system_info', args: {} }],
  });
  console.log('Create goal result:', JSON.stringify(createResult, null, 2));

  console.log('\n=== Example 2: Create a Thinking Goal ===');
  // Create a goal that triggers LLM thinking
  const thinkGoal = await framework.executeTool('ambient_goals', {
    action: 'create',
    title: 'Periodic Reflection',
    description: 'Regularly reflect on system state and suggest improvements',
    priority: 5,
    actions: [
      { id: 'reflect_1', type: 'think', topic: 'System state review', mode: 'reflect', depth: 3 },
    ],
  });
  console.log('Create thinking goal result:', JSON.stringify(thinkGoal, null, 2));

  console.log('\n=== Example 3: List All Goals ===');
  const listResult = await framework.executeTool('ambient_goals', {
    action: 'list',
  });
  console.log('Goals list:', JSON.stringify(listResult, null, 2));

  console.log('\n=== Example 4: Get Ambient Status ===');
  const statusResult = await framework.executeTool('ambient_status', {});
  console.log('Status:', JSON.stringify(statusResult, null, 2));

  console.log('\n=== Example 5: Store a Memory ===');
  const storeResult = await framework.executeTool('ambient_remember', {
    action: 'store',
    content: 'Important: System check showed high CPU usage at 14:30',
    key: 'cpu_alert_1',
  });
  console.log('Store memory result:', JSON.stringify(storeResult, null, 2));

  console.log('\n=== Example 6: Retrieve Memories ===');
  const retrieveResult = await framework.executeTool('ambient_remember', {
    action: 'retrieve',
    limit: 5,
  });
  console.log('Retrieve memories result:', JSON.stringify(retrieveResult, null, 2));

  console.log('\n=== Example 7: Search Memories ===');
  const searchResult = await framework.executeTool('ambient_remember', {
    action: 'search',
    query: 'CPU',
  });
  console.log('Search memories result:', JSON.stringify(searchResult, null, 2));

  console.log('\n=== Example 8: Trigger Thinking ===');
  const thinkResult = await framework.executeTool('ambient_think', {
    mode: 'brainstorm',
    topic: 'What improvements could be made to the current system?',
    depth: 3,
  });
  console.log('Think result:', JSON.stringify(thinkResult, null, 2));

  console.log('\n=== Example 9: Control Loop ===');
  console.log('Pausing loop...');
  const pauseResult = await framework.executeTool('ambient_control', {
    action: 'pause',
  });
  console.log('Pause result:', JSON.stringify(pauseResult, null, 2));

  await new Promise((resolve) => setTimeout(resolve, 1000));

  console.log('Resuming loop...');
  const resumeResult = await framework.executeTool('ambient_control', {
    action: 'resume',
  });
  console.log('Resume result:', JSON.stringify(resumeResult, null, 2));

  console.log('\n=== Example 10: Adjust Loop Settings ===');
  const adjustResult = await framework.executeTool('ambient_control', {
    action: 'adjust',
    tickInterval: 10000, // 10 seconds
    cooldownPeriod: 5000, // 5 seconds
  });
  console.log('Adjust result:', JSON.stringify(adjustResult, null, 2));

  console.log('\n=== Example 11: Get Final Status ===');
  const finalStatus = await framework.executeTool('ambient_status', {});
  console.log('Final status:', JSON.stringify(finalStatus, null, 2));

  console.log('\n=== Example 12: Activate a Pending Goal ===');
  // First create a pending goal (without auto-activation conditions)
  const newGoal = await framework.executeTool('ambient_goals', {
    action: 'create',
    title: 'Inactive Test Goal',
    description: 'A goal that starts inactive',
    priority: 3,
    actions: [],
  });
  console.log('Created inactive goal:', newGoal.goal ? newGoal.goal.id : 'N/A');

  if (newGoal.goal) {
    console.log('Activating goal...');
    const activateResult = await framework.executeTool('ambient_goals', {
      action: 'activate',
      goalId: newGoal.goal.id,
    });
    console.log('Activate result:', JSON.stringify(activateResult, null, 2));
  }

  console.log('\n=== Example 13: Update a Goal ===');
  const goals = await framework.executeTool('ambient_goals', { action: 'list' });
  if (goals.goals && goals.goals.length > 0) {
    const goalToUpdate = goals.goals[0];
    console.log(`Updating goal ${goalToUpdate.id}...`);
    const updateResult = await framework.executeTool('ambient_goals', {
      action: 'update',
      goalId: goalToUpdate.id,
      priority: 10,
    });
    console.log('Update result:', JSON.stringify(updateResult, null, 2));
  }

  console.log('\n=== Example 14: Delete a Goal ===');
  const deleteGoal = await framework.executeTool('ambient_goals', {
    action: 'create',
    title: 'Goal to Delete',
    description: 'This will be deleted',
    priority: 1,
  });
  if (deleteGoal.goal) {
    console.log(`Created goal to delete: ${deleteGoal.goal.id}`);
    const deleteResult = await framework.executeTool('ambient_goals', {
      action: 'delete',
      goalId: deleteGoal.goal.id,
    });
    console.log('Delete result:', JSON.stringify(deleteResult, null, 2));
  }

  console.log('\n=== All Examples Completed ===');
  console.log('Check .agent/data/ambient/ for persisted data');

  // Cleanup
  console.log('\nShutting down...');
  await framework.destroy();
}

main().catch((err) => {
  console.error('Example error:', err);
  process.exit(1);
});
