/**
 * Savings Reporter agent for Token.
 *
 * Generates natural-language savings reports comparing local inference
 * costs vs what the user would have paid using cloud APIs.
 */

interface SavingsData {
  localRequests: number;
  cloudRequests: number;
  totalRequests: number;
  localCost: number; // electricity + amortized hardware
  cloudCost: number; // actual cloud API spend
  cloudEquivalentCost: number; // what local requests would have cost on cloud
  periodDays: number;
}

interface SavingsReport {
  summary: string;
  totalSaved: number;
  savingsPercentage: number;
  projectedMonthlySavings: number;
  breakdown: string;
  recommendation: string;
}

/**
 * Cloud API pricing reference (per 1M tokens, approximate Feb 2026).
 */
const CLOUD_PRICING: Record<string, { input: number; output: number }> = {
  "gpt-4o": { input: 2.5, output: 10.0 },
  "gpt-4o-mini": { input: 0.15, output: 0.6 },
  "claude-sonnet-4-6": { input: 3.0, output: 15.0 },
  "claude-haiku-4-5": { input: 0.8, output: 4.0 },
  "gemini-2.5-flash": { input: 0.15, output: 0.6 },
};

/**
 * Estimated local inference cost (electricity only, per 1M tokens).
 * Based on ~300W GPU at $0.12/kWh, ~30 tokens/sec for 7B model.
 */
const LOCAL_COST_PER_M_TOKENS = 0.03;

/**
 * Generate a natural-language savings report.
 */
function generateSavingsReport(data: SavingsData): SavingsReport {
  const totalSaved = data.cloudEquivalentCost - data.localCost;
  const wouldHaveSpent = data.cloudEquivalentCost + data.cloudCost;
  const savingsPercentage = wouldHaveSpent > 0 ? (totalSaved / wouldHaveSpent) * 100 : 0;
  const projectedMonthlySavings =
    data.periodDays > 0 ? (totalSaved / data.periodDays) * 30 : 0;


  // Summary
  let summary: string;
  if (totalSaved > 100) {
    summary = `You saved $${totalSaved.toFixed(2)} over the last ${data.periodDays} days by running inference locally. That's ${savingsPercentage.toFixed(0)}% less than cloud-only.`;
  } else if (totalSaved > 10) {
    summary = `Local inference saved you $${totalSaved.toFixed(2)} over ${data.periodDays} days. Your GPUs are paying for themselves.`;
  } else if (totalSaved > 0) {
    summary = `You've saved $${totalSaved.toFixed(2)} so far. As usage grows, savings compound — local inference gets cheaper per request.`;
  } else {
    summary =
      "You're just getting started. Once local inference ramps up, expect significant savings vs cloud APIs.";
  }

  // Breakdown
  const breakdown = [
    `Period: ${data.periodDays} days`,
    `Total requests: ${data.totalRequests.toLocaleString()} (${data.localRequests.toLocaleString()} local, ${data.cloudRequests.toLocaleString()} cloud)`,
    `Cloud API spend: $${data.cloudCost.toFixed(2)}`,
    `Local electricity cost (est.): $${data.localCost.toFixed(2)}`,
    `Cloud equivalent of local: $${data.cloudEquivalentCost.toFixed(2)}`,
    `Net savings: $${totalSaved.toFixed(2)} (${savingsPercentage.toFixed(0)}%)`,
  ].join("\n");

  // Recommendation
  let recommendation: string;
  if (data.localRequests === 0) {
    recommendation =
      "You haven't used local inference yet. Connect a device with `llmhosts up` to start saving.";
  } else if (savingsPercentage < 30) {
    recommendation =
      "Consider routing more requests locally. Enable prefer_local in your config to maximize savings.";
  } else if (savingsPercentage < 70) {
    recommendation =
      "Good balance of local and cloud. Consider adding another GPU to handle peak loads locally.";
  } else {
    recommendation =
      "Excellent local utilization. You're getting maximum value from your hardware.";
  }

  return {
    summary,
    totalSaved,
    savingsPercentage,
    projectedMonthlySavings,
    breakdown,
    recommendation,
  };
}

/**
 * Format savings report as a system prompt section.
 */
function formatSavingsPrompt(report: SavingsReport): string {
  return [
    "## Savings Report",
    report.summary,
    "",
    "### Breakdown",
    report.breakdown,
    "",
    `Projected monthly savings: $${report.projectedMonthlySavings.toFixed(2)}`,
    "",
    `Recommendation: ${report.recommendation}`,
  ].join("\n");
}

export { CLOUD_PRICING, LOCAL_COST_PER_M_TOKENS, generateSavingsReport, formatSavingsPrompt };
export type { SavingsData, SavingsReport };
