import { DEFAULT_INSTANCE_TYPE } from "./instanceTypes";

// Cost estimation for preview EC2 instances.
//
// PP bills nothing itself; the EC2 runs in the user's own AWS account, so this
// is an estimate derived from on-demand pricing and how long each instance ran.
// It is deliberately not tied to AWS Cost Explorer / billing APIs: those lag by
// hours-to-a-day and would need extra IAM permissions. Uptime times hourly rate
// is accurate enough for a dashboard and updates live.
//
// Rates below are USD/hour for Linux on-demand in us-east-1. Other regions cost
// a little more, so treat the number as a lower-bound ballpark. Keep these in
// sync with the table shown in frontend RepoConfig.tsx.

export const INSTANCE_HOURLY_USD: Record<string, number> = {
  // Legacy t2 rates are retained for historical previews that were actually
  // launched as t2 before the default moved to current-generation instances.
  "t2.micro": 0.0116,
  "t2.small": 0.023,
  "t2.medium": 0.0464,
  "t2.large": 0.0928,
  "t3.micro": 0.0104,
  "t3.small": 0.0208,
  "t3.medium": 0.0416,
  "t3.large": 0.0832,
  "t3a.medium": 0.0376,
  "t3a.large": 0.0752,
  "t4g.medium": 0.0336,
  "t4g.large": 0.0672,
  "m5.large": 0.096,
  "m5.xlarge": 0.192,
  "c5.large": 0.085,
  "c5.xlarge": 0.17,
};

// Fallback when the instance type is unknown/custom: use the current default so
// an estimate is still shown rather than $0.
const DEFAULT_HOURLY_USD = INSTANCE_HOURLY_USD[DEFAULT_INSTANCE_TYPE];

export function hourlyRateUsd(instanceType?: string | null): number {
  if (!instanceType) return DEFAULT_HOURLY_USD;
  return INSTANCE_HOURLY_USD[instanceType] ?? DEFAULT_HOURLY_USD;
}

// Cost of a single instance session from launch to now/termination at the given
// type's hourly rate. Clamps negatives to 0 in case clocks disagree.
export function sessionCostUsd(
  launchedAt: Date,
  until: Date,
  instanceType?: string | null,
): number {
  const hours = Math.max(0, (until.getTime() - launchedAt.getTime()) / 3_600_000);
  return hours * hourlyRateUsd(instanceType);
}

// The fields cost calculation needs off a Preview row.
export interface PreviewCostFields {
  accumulatedCostUsd: number;
  instanceLaunchedAt: Date | null;
  instanceType: string | null;
}

// Total estimated cost for a preview: finalized cost of past sessions plus the
// live session's accrual so far, if an instance is currently running.
export function computePreviewCostUsd(p: PreviewCostFields, now: Date = new Date()): number {
  let total = p.accumulatedCostUsd || 0;
  if (p.instanceLaunchedAt) {
    total += sessionCostUsd(p.instanceLaunchedAt, now, p.instanceType);
  }
  return total;
}
