import { DashClaw } from '../sdk/dashclaw.js';
import dotenv from 'dotenv';
dotenv.config();

/**
 * Node.js Parity for Kimi/Moonshot Example
 * Demonstrates: guard -> createAction -> recordAssumption -> updateOutcome
 *
 * The `openai` package is loaded lazily inside main() so this file can be
 * imported (e.g. for static analysis) without pulling in the SDK.
 */

const claw = new DashClaw({
  baseUrl: process.env.DASHCLAW_BASE_URL || 'http://localhost:3000',
  apiKey: process.env.DASHCLAW_API_KEY,
  agentId: 'moonshot-email-agent',
  agentName: 'Moonshot Email Agent',
});

function sendEmail(recipient, subject, body) {
  console.log(`Sending email to ${recipient} with subject: ${subject}`);
  return { ok: true, recipient, subject };
}

async function main() {
  const userPrompt = 'Write a short follow up email to Acme asking for a meeting next week.';

  const { default: OpenAI } = await import('openai');
  const moonshot = new OpenAI({
    apiKey: process.env.MOONSHOT_API_KEY,
    baseURL: 'https://api.moonshot.ai/v1',
  });

  const completion = await moonshot.chat.completions.create({
    model: 'kimi-k2-turbo-preview',
    messages: [
      {
        role: 'system',
        content: 'You are Kimi, an AI assistant provided by Moonshot AI.'
      },
      { role: 'user', content: userPrompt },
    ],
    temperature: 0.6,
  });

  const draftedEmail = completion.choices[0].message.content;

  // 1. Guard check
  const { decision } = await claw.guard({
    action_type: 'message',
    risk_score: 72,
    systems_touched: ['email', 'moonshot_api'],
    reversible: false,
    declared_goal: 'Draft and send outbound follow up email to a prospect',
  });

  console.log('Guard result:', decision);

  if (decision === 'block' || decision === 'require_approval') {
    console.log('DashClaw stopped the action:', decision);
    return;
  }

  // 2. Create the action
  const { action } = await claw.createAction({
    action_type: 'message',
    declared_goal: 'Send outbound follow up email to Acme',
    reasoning: 'User requested a follow up email generated by Moonshot.',
    systems_touched: ['email', 'moonshot_api'],
    input_summary: userPrompt,
    reversible: false,
    risk_score: 72,
    confidence: 84,
  });

  const actionId = action.action_id;
  console.log('Action response:', actionId);

  // 3. Register Assumption
  await claw.recordAssumption({
    action_id: actionId,
    assumption: 'The recipient is a valid business contact and outreach is authorized.',
    basis: 'User initiated the request and provided the business context.',
    validated: false,
  });

  // 4. Update Outcome
  try {
    const result = sendEmail(
      'team@acme.com',
      'Quick follow up',
      draftedEmail
    );

    await claw.updateOutcome(actionId, {
      status: 'completed',
      output_summary: `Email sent successfully to ${result.recipient}`,
    });

    console.log('Success. Check DashClaw dashboard for the action trace:', actionId);

  } catch (e) {
    await claw.updateOutcome(actionId, {
      status: 'failed',
      output_summary: `Email send failed: ${e.message}`,
    });
    throw e;
  }
}

main().catch(console.error);
