/**
 * Private LLM cost study.
 *
 * Runs the same cost engine the live calculator uses across every combination
 * of its real inputs, then compares each private deployment against current API
 * list prices. Writes the full dataset and a summary the guide page renders.
 *
 * Run (Node 23.6+ executes the TypeScript engine directly, no build step):
 *   node scripts/study-private-llm-cost.mjs      inside the NavyaAI repo
 *   node study.mjs                               downloaded, next to engine.mts
 *
 * Outputs (in the repo):
 *   public/data/private-llm-cost-study.csv            every scenario, one row each
 *   lib/studies/private-llm-cost.json                 derived findings for the page
 *   public/data/private-llm-cost-study/study.mjs      this script, published
 *   public/data/private-llm-cost-study/engine.mts     the cost engine, published
 * Outputs (downloaded): the CSV and a summary JSON, next to the script.
 *
 * Nothing here is typed by hand. To refresh the study, re-verify API_PRICING in
 * the engine, bump API_PRICING_VERIFIED_ON, and run this again.
 */
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

// This script runs in two places. Inside the NavyaAI repo it imports the live
// calculator's cost engine. Published on navyaai.com it sits next to a copy of
// that engine (engine.mts), so anyone can download both files and re-run the study.
const here = dirname(fileURLToPath(import.meta.url));
const STANDALONE = existsSync(join(here, "engine.mts"));
const ENGINE_PATH = STANDALONE ? join(here, "engine.mts") : join(here, "../lib/agents/onprem-estimator/engine.ts");
const {
  API_PRICING,
  API_PRICING_VERIFIED_ON,
  WORKLOAD_SHAPES,
  estimateMonthlyCost,
  estimateReplicaThroughput,
  runEstimate,
} = await import(ENGINE_PATH);

const root = join(here, "..");

// ── Grid: the calculator's own input space ──
const MODEL_SIZES = ["7b", "13b", "34b", "70b", "120b+"];
// INT8 is the calculator's default; FP16 is the unquantized comparison.
const PRECISIONS = ["int8", "fp16"];
// "edge-device" is priced identically to "on-prem-server" by the engine, so it
// would only duplicate rows.
const DEPLOYMENTS = ["cloud-gpu", "on-prem-server"];
const LATENCIES = ["real-time", "interactive", "batch"];
const USE_CASES = ["chatbot", "code-assistant", "document-processing", "rag-search", "content-generation"];
const CONCURRENCY = [5, 25, 100];

// The engine prices hardware, power and per-GPU maintenance. It does not price
// the people who keep a serving stack alive. This is the low end of the
// $1,500-$2,500/month range we quote for one production stack; the study
// reports results both without and with it.
const OPS_FLOOR_USD = 1500;

// API prices this engine shipped with until Sept 2026 (recoverable from git
// history). Kept so the study can measure how far break-even moved.
const PRICING_2024 = {
  gpt4o: { name: "OpenAI GPT-4o", input: 2.5, output: 10.0 },
  claudeSonnet: { name: "Anthropic Claude Sonnet", input: 3.0, output: 15.0 },
};

// Measured throughput from our Llama 3 70B benchmark (vLLM 0.4.3), published in
// content/blogs/token-tax-inference-optimization.md. The engine's throughput
// model is checked against every one of these on each run.
const BENCHMARK_POINTS = [
  { label: "FP16, 2x A100 80GB (TP=2), batch 1", modelSize: "70b", precision: "fp16", gpuKey: "A100", tensorParallel: 2, batch: 1, measuredTps: 25 },
  { label: "FP16, 2x A100 80GB (TP=2), batch 32", modelSize: "70b", precision: "fp16", gpuKey: "A100", tensorParallel: 2, batch: 32, measuredTps: 680 },
  { label: "INT8, 1x H100 80GB, batch 1", modelSize: "70b", precision: "int8", gpuKey: "H100", tensorParallel: 1, batch: 1, measuredTps: 42 },
  { label: "INT8, 1x H100 80GB, batch 32", modelSize: "70b", precision: "int8", gpuKey: "H100", tensorParallel: 1, batch: 32, measuredTps: 1150 },
];
// Fail the run if the model drifts from the measurements by more than this.
const MAX_CALIBRATION_ERROR_PCT = 15;

const DAYS_PER_MONTH = 30.4;
const SECONDS_PER_MONTH = 730 * 3600;
const tiers = Object.entries(API_PRICING).map(([key, p]) => ({ key, ...p }));

const blended = (price, shape) => {
  const total = shape.avgInputTokens + shape.avgOutputTokens;
  return (price.input * shape.avgInputTokens + price.output * shape.avgOutputTokens) / total;
};

const median = (xs) => {
  if (xs.length === 0) return null;
  const s = [...xs].sort((a, b) => a - b);
  const mid = Math.floor(s.length / 2);
  return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
};

const round = (n, dp = 2) => (n === null || !Number.isFinite(n) ? null : Math.round(n * 10 ** dp) / 10 ** dp);
const pct = (n, d) => (d === 0 ? null : round((n / d) * 100, 1));

// ── Calibration: does the throughput model reproduce what we measured? ──
const calibrationPoints = BENCHMARK_POINTS.map((p) => {
  const modeledTps = estimateReplicaThroughput(p);
  return {
    label: p.label,
    measuredTps: p.measuredTps,
    modeledTps: Math.round(modeledTps),
    errorPct: round((modeledTps / p.measuredTps - 1) * 100, 1),
  };
});
const worstErrorPct = Math.max(...calibrationPoints.map((p) => Math.abs(p.errorPct)));
if (worstErrorPct > MAX_CALIBRATION_ERROR_PCT) {
  throw new Error(`Throughput model is ${worstErrorPct}% off a measured benchmark point (limit ${MAX_CALIBRATION_ERROR_PCT}%). Fix the engine before publishing.`);
}

// Our published "$0.47 per million tokens" divides one on-prem H100's monthly cost
// by the tokens it produces at the best measured throughput, running flat out all
// month. Show what the same measurement costs at a realistic duty cycle.
const BEST_MEASURED_TPS = 1560; // INT8 + KV-cache pruning + tuned batching, 1x H100, batch 32
const h100Monthly = estimateMonthlyCost("H100", 1, false);
const benchmarkCost = {
  publishedUsdPerM: 0.47,
  bestMeasuredTps: BEST_MEASURED_TPS,
  h100OnPremMonthlyUsd: Math.round(h100Monthly),
  usdPerMAt100PctBusy: round(h100Monthly / ((BEST_MEASURED_TPS * SECONDS_PER_MONTH) / 1e6), 2),
  usdPerMAt65PctBusy: round(h100Monthly / ((BEST_MEASURED_TPS * SECONDS_PER_MONTH * 0.65) / 1e6), 2),
};

// ── Run every scenario ──
const rows = [];
for (const modelSize of MODEL_SIZES) {
  for (const precision of PRECISIONS) {
    for (const deploymentType of DEPLOYMENTS) {
      for (const latencyRequirement of LATENCIES) {
        for (const useCase of USE_CASES) {
          for (const concurrentUsers of CONCURRENCY) {
            // Monthly cost and capacity do not depend on volume in this engine:
            // hardware is sized by model, latency and concurrency. So private cost
            // is a fixed monthly figure, API cost is linear in volume, and the
            // crossover is exact: fixed cost / API rate.
            const r = runEstimate({ modelSize, precision, deploymentType, latencyRequirement, useCase, concurrentUsers, monthlyTokenVolume: 1 });
            const shape = WORKLOAD_SHAPES[useCase];
            const privateMonthly = r.costs.amortizedMonthly;
            const capacityM = r.throughput.monthlyCapacityMillionTokens;

            const row = {
              modelSize, precision, deploymentType, latencyRequirement, useCase, concurrentUsers,
              gpu: r.hardware.gpuName,
              gpuCount: r.hardware.gpuCount,
              replicas: r.hardware.replicas,
              meetsLatency: r.throughput.meetsLatencyTarget,
              perUserTps: r.throughput.perUserTokensPerSec,
              privateMonthlyUsd: privateMonthly,
              capacityMTokensPerMonth: capacityM,
              unitCostAtCapacityUsdPerM: capacityM > 0 ? round(privateMonthly / capacityM, 3) : null,
              tiers: {},
            };

            for (const t of tiers) {
              const rate = blended(t, shape);
              const crossoverM = privateMonthly / rate;
              const crossoverOpsM = (privateMonthly + OPS_FLOOR_USD) / rate;
              row.tiers[t.key] = {
                apiRateUsdPerM: round(rate, 3),
                crossoverMTokensPerMonth: round(crossoverM, 1),
                // Self-hosting can only win if the hardware can actually serve
                // the break-even volume.
                reachable: crossoverM <= capacityM,
                reachableWithOpsFloor: crossoverOpsM <= capacityM,
              };
            }

            const rate2024 = (blended(PRICING_2024.gpt4o, shape) + blended(PRICING_2024.claudeSonnet, shape)) / 2;
            const rateMid2026 = (blended(API_PRICING.openaiMid, shape) + blended(API_PRICING.anthropicMid, shape)) / 2;
            row.crossover2024M = privateMonthly / rate2024;
            row.crossoverMid2026M = privateMonthly / rateMid2026;

            rows.push(row);
          }
        }
      }
    }
  }
}

// ── Findings ──
const summarize = (subset) => {
  const out = {};
  for (const t of tiers) {
    const reachable = subset.filter((r) => r.tiers[t.key].reachable);
    out[t.key] = {
      shareSelfHostCanWinPct: pct(reachable.length, subset.length),
      shareWithOpsFloorPct: pct(subset.filter((r) => r.tiers[t.key].reachableWithOpsFloor).length, subset.length),
      medianBreakEvenMTokensPerDay: round(median(reachable.map((r) => r.tiers[t.key].crossoverMTokensPerMonth / DAYS_PER_MONTH)), 1),
    };
  }
  return out;
};

const overall = summarize(rows);
const tierFindings = tiers.map((t) => ({
  key: t.key,
  name: t.name,
  tier: t.tier,
  inputUsdPerM: t.input,
  outputUsdPerM: t.output,
  shareScenariosSelfHostCanWinPct: overall[t.key].shareSelfHostCanWinPct,
  shareWithOpsFloorPct: overall[t.key].shareWithOpsFloorPct,
  medianBreakEvenMTokensPerDay: overall[t.key].medianBreakEvenMTokensPerDay,
}));

const byModelSize = MODEL_SIZES.map((m) => {
  const subset = rows.filter((r) => r.modelSize === m && r.precision === "int8");
  return {
    modelSize: m,
    scenarios: subset.length,
    medianPrivateMonthlyUsd: round(median(subset.map((r) => r.privateMonthlyUsd)), 0),
    medianUnitCostAtCapacityUsdPerM: round(median(subset.map((r) => r.unitCostAtCapacityUsdPerM).filter((x) => x !== null)), 2),
    tiers: summarize(subset),
  };
});

const byPrecision = PRECISIONS.map((p) => {
  const subset = rows.filter((r) => r.precision === p);
  return {
    precision: p,
    scenarios: subset.length,
    medianPrivateMonthlyUsd: round(median(subset.map((r) => r.privateMonthlyUsd)), 0),
    tiers: summarize(subset),
  };
});

const byDeployment = DEPLOYMENTS.map((d) => {
  const subset = rows.filter((r) => r.deploymentType === d);
  return { deploymentType: d, scenarios: subset.length, tiers: summarize(subset) };
});

const byConcurrency = CONCURRENCY.map((c) => {
  const subset = rows.filter((r) => r.concurrentUsers === c);
  return { concurrentUsers: c, scenarios: subset.length, tiers: summarize(subset) };
});

// How far did break-even move when the API price sheet was updated?
const shift = {
  medianBreakEvenVolumeChangePct: round(median(rows.map((r) => (r.crossoverMid2026M / r.crossover2024M - 1) * 100)), 1),
  pricing2024: Object.values(PRICING_2024),
};

// Worked example, generated rather than typed: a 70B chatbot at 60M tokens/day.
const EXAMPLE_TOKENS_PER_DAY_M = 60;
const exampleVolumeM = Math.round(EXAMPLE_TOKENS_PER_DAY_M * DAYS_PER_MONTH);
const exampleFields = { modelSize: "70b", useCase: "chatbot", latencyRequirement: "interactive", concurrentUsers: 32, monthlyTokenVolume: exampleVolumeM };
const exampleRun = (deploymentType, precision) => {
  const r = runEstimate({ ...exampleFields, deploymentType, precision });
  return {
    deploymentType, precision,
    hardware: `${r.hardware.gpuCount}x ${r.hardware.gpuName}`,
    monthlyUsd: r.costs.amortizedMonthly,
    upfrontUsd: r.upfront.total,
    usdPerM: r.costs.costPerMillionTokensBlended,
    utilizationPct: r.costs.gpuUtilizationPercent,
    perUserTps: r.throughput.perUserTokensPerSec,
  };
};
const chatbot = WORKLOAD_SHAPES.chatbot;
const workedExample = {
  tokensPerDayM: EXAMPLE_TOKENS_PER_DAY_M,
  monthlyVolumeM: exampleVolumeM,
  concurrentUsers: exampleFields.concurrentUsers,
  inputOutputMix: `${chatbot.avgInputTokens}:${chatbot.avgOutputTokens}`,
  selfHost: [exampleRun("on-prem-server", "int8"), exampleRun("cloud-gpu", "int8"), exampleRun("on-prem-server", "fp16")],
  api: tiers.map((t) => ({ key: t.key, name: t.name, blendedUsdPerM: round(blended(t, chatbot), 2), monthlyUsd: Math.round(blended(t, chatbot) * exampleVolumeM) })),
};

const summary = {
  generatedOn: new Date().toISOString().slice(0, 10),
  pricingVerifiedOn: API_PRICING_VERIFIED_ON,
  scenarioCount: rows.length,
  comparisonCount: rows.length * tiers.length,
  opsFloorUsd: OPS_FLOOR_USD,
  latencyMissCount: rows.filter((r) => !r.meetsLatency).length,
  grid: { modelSizes: MODEL_SIZES, precisions: PRECISIONS, deployments: DEPLOYMENTS, latencies: LATENCIES, useCases: USE_CASES, concurrency: CONCURRENCY },
  tiers: tierFindings,
  byModelSize,
  byPrecision,
  byDeployment,
  byConcurrency,
  shift,
  calibration: { points: calibrationPoints, worstErrorPct, limitPct: MAX_CALIBRATION_ERROR_PCT },
  benchmarkCost,
  workedExample,
};

// ── Write outputs ──
const header = [
  "model_size", "precision", "deployment", "latency", "use_case", "concurrent_users", "gpu", "gpu_count", "replicas",
  "meets_latency_target", "per_user_tokens_per_sec",
  "private_monthly_usd", "capacity_m_tokens_per_month", "unit_cost_at_capacity_usd_per_m",
  ...tiers.flatMap((t) => [`${t.key}_api_rate_usd_per_m`, `${t.key}_break_even_m_tokens_per_month`, `${t.key}_reachable`, `${t.key}_reachable_with_ops_floor`]),
];
const csv = [
  header.join(","),
  ...rows.map((r) => [
    r.modelSize, r.precision, r.deploymentType, r.latencyRequirement, r.useCase, r.concurrentUsers, `"${r.gpu}"`, r.gpuCount, r.replicas,
    r.meetsLatency, r.perUserTps,
    r.privateMonthlyUsd, r.capacityMTokensPerMonth, r.unitCostAtCapacityUsdPerM ?? "",
    ...tiers.flatMap((t) => {
      const x = r.tiers[t.key];
      return [x.apiRateUsdPerM, x.crossoverMTokensPerMonth, x.reachable, x.reachableWithOpsFloor];
    }),
  ].join(",")),
].join("\n");

// Standalone: write next to the script. In the repo: write where the site reads them.
const csvPath = STANDALONE ? join(here, "private-llm-cost-study.csv") : join(root, "public/data/private-llm-cost-study.csv");
const jsonPath = STANDALONE ? join(here, "private-llm-cost-study.summary.json") : join(root, "lib/studies/private-llm-cost.json");
mkdirSync(dirname(csvPath), { recursive: true });
mkdirSync(dirname(jsonPath), { recursive: true });
writeFileSync(csvPath, csv + "\n");
writeFileSync(jsonPath, JSON.stringify(summary, null, 2) + "\n");

// Publish the exact code that produced these numbers alongside the dataset. The
// repo is private, so a link to it proves nothing to a reader; these two files do.
// They are copied on every run, so they cannot drift from what generated the data.
if (!STANDALONE) {
  const sourceDir = join(root, "public/data/private-llm-cost-study");
  mkdirSync(sourceDir, { recursive: true });
  copyFileSync(fileURLToPath(import.meta.url), join(sourceDir, "study.mjs"));
  // .mts, not .ts: web servers send .ts as video/mp2t (MPEG transport stream).
  copyFileSync(ENGINE_PATH, join(sourceDir, "engine.mts"));
}

console.log(JSON.stringify(summary, null, 2));
console.error(`\nWrote ${rows.length} scenarios -> ${csvPath}\nWrote summary -> ${jsonPath}`);
