/**
 * TealGroq Quickstart
 *
 * Demonstrates a guarded Groq client with input guardrails, low-latency timing,
 * a daily budget, and per-request cost tracking.
 *
 * Run with:
 *
 *   GROQ_API_KEY=your-key npx ts-node --project examples/groq-quickstart/tsconfig.json examples/groq-quickstart/index.ts
 */

import {
  BudgetManager,
  ContentModerationGuardrail,
  CostTracker,
  GuardrailEngine,
  InMemoryCostStorage,
  PIIDetectionGuardrail,
} from 'tealtiger';
import { GROQ_PRICING, TealGroq } from 'tealtiger/providers/groq';

const MODEL = 'llama-3.1-8b-instant';

function createGuardrailEngine(): GuardrailEngine {
  const guardrailEngine = new GuardrailEngine();

  guardrailEngine.registerGuardrail(new PIIDetectionGuardrail({
    name: 'pii-detection',
    enabled: true,
    action: 'redact',
  }));

  guardrailEngine.registerGuardrail(new ContentModerationGuardrail({
    name: 'content-moderation',
    enabled: true,
    action: 'block',
    useOpenAI: false,
  }));

  return guardrailEngine;
}

function createCostTracker(): CostTracker {
  const costTracker = new CostTracker({
    enabled: true,
    persistRecords: true,
    enableBudgets: true,
    enableAlerts: true,
  });

  const pricing = GROQ_PRICING[MODEL];
  costTracker.addCustomPricing(MODEL, {
    provider: 'custom',
    inputCostPer1K: pricing.input,
    outputCostPer1K: pricing.output,
    lastUpdated: '2026-05-23',
  });

  return costTracker;
}

function formatSeconds(seconds: number | undefined): string {
  return seconds == null ? 'not reported' : `${(seconds * 1000).toFixed(1)} ms`;
}

async function main() {
  const guardrailEngine = createGuardrailEngine();
  const costStorage = new InMemoryCostStorage();
  const costTracker = createCostTracker();
  const budgetManager = new BudgetManager(costStorage);

  budgetManager.createBudget({
    name: 'Groq Quickstart Daily Budget',
    limit: 5.0,
    period: 'daily',
    alertThresholds: [50, 75, 90],
    action: 'alert',
    enabled: true,
  });

  const client = new TealGroq({
    apiKey: process.env.GROQ_API_KEY || 'your-groq-api-key',
    agentId: 'groq-quickstart-agent',
    model: MODEL,
    guardrailEngine,
    costTracker,
    budgetManager,
    costStorage,
  });

  console.log('--- Basic Groq request ---');
  const startedAt = performance.now();
  const basic = await client.chat.completions.create({
    model: MODEL,
    messages: [
      {
        role: 'system',
        content: 'You are a concise security engineer.',
      },
      {
        role: 'user',
        content: 'In one sentence, what does TealTiger add around Groq calls?',
      },
    ],
    max_tokens: 120,
  });
  const elapsedMs = performance.now() - startedAt;

  console.log('Response:', basic.choices[0].message.content);
  console.log(`Measured latency: ${elapsedMs.toFixed(1)} ms`);
  console.log(`Groq reported total time: ${formatSeconds(basic.usage.total_time)}`);
  console.log(`Groq queue time: ${formatSeconds(basic.usage.queue_time)}`);

  if (basic.security?.costRecord) {
    console.log(`Cost: $${basic.security.costRecord.actualCost.toFixed(6)}`);
    console.log(`Tokens: ${basic.security.costRecord.actualTokens.totalTokens}`);
  }

  console.log('\n--- PII guardrail request ---');
  const guarded = await client.chat.completions.create({
    model: MODEL,
    messages: [
      {
        role: 'user',
        content: 'Draft a support reply for Taylor at taylor@example.com without repeating the email address.',
      },
    ],
    max_tokens: 120,
  });

  const inputGuardrails = guarded.security?.guardrailResult;
  const piiResult = inputGuardrails?.results.find(
    (result: { guardrailName: string }) => result.guardrailName === 'pii-detection',
  );
  const redactedText = piiResult?.result?.metadata?.redactedText;

  console.log('Guardrail summary:', inputGuardrails?.getSummary());
  if (redactedText) {
    console.log('Redacted input:', redactedText);
  }
  if (guarded.security?.costRecord) {
    console.log(`Cost: $${guarded.security.costRecord.actualCost.toFixed(6)}`);
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const costSummary = await costStorage.getSummary(today, new Date(), 'groq-quickstart-agent');

  console.log('\n--- Cost summary ---');
  console.log(`Requests tracked: ${costSummary.totalRequests}`);
  console.log(`Total cost: $${costSummary.totalCost.toFixed(6)}`);
}

main().catch((error) => {
  console.error('Groq quickstart failed:', error);
  process.exit(1);
});
