import type { HrAggregateScoreBreakdown } from "@/lib/human-capital/types";

const WEIGHTS = {
  churn: 0.35,
  tenure: 0.25,
  headcountStability: 0.2,
  kpiCompliance: 0.2,
} as const;

function clamp(value: number, min = 0, max = 100): number {
  return Math.min(max, Math.max(min, value));
}

function round(value: number): number {
  return Math.round(value * 10) / 10;
}

export function churnPct(exits: number, averageHeadcount: number): number {
  if (averageHeadcount <= 0) {
    return 0;
  }

  return round((exits / averageHeadcount) * 100);
}

export function churnScoreFromPct(monthlyChurnPct: number): number {
  return round(clamp(100 - monthlyChurnPct * 5));
}

export function tenureScoreFromMedianMonths(medianTenureMonths: number): number {
  return round(clamp((medianTenureMonths / 36) * 100));
}

export function headcountStabilityScore(activeHeadcount: number, previousHeadcount: number): number {
  if (previousHeadcount <= 0) {
    return 100;
  }

  const deltaPct = Math.abs(activeHeadcount - previousHeadcount) / previousHeadcount;
  return round(clamp(100 - deltaPct * 100));
}

export function buildHrAggregateScore(input: {
  monthlyChurnPct: number;
  medianTenureMonths: number;
  activeHeadcount: number;
  previousHeadcount: number;
  kpiCompliancePct: number;
}): HrAggregateScoreBreakdown {
  const churnScore = churnScoreFromPct(input.monthlyChurnPct);
  const tenureScore = tenureScoreFromMedianMonths(input.medianTenureMonths);
  const headcountStability = headcountStabilityScore(input.activeHeadcount, input.previousHeadcount);
  const kpiCompliance = round(clamp(input.kpiCompliancePct));

  const totalScore = round(
    churnScore * WEIGHTS.churn +
      tenureScore * WEIGHTS.tenure +
      headcountStability * WEIGHTS.headcountStability +
      kpiCompliance * WEIGHTS.kpiCompliance
  );

  return {
    totalScore,
    churnScore,
    tenureScore,
    headcountStabilityScore: headcountStability,
    kpiComplianceScore: kpiCompliance,
    weights: { ...WEIGHTS },
  };
}
