import { prisma } from "../prisma.js";
import { Prisma } from "@prisma/client";
import { computeAttendanceCapturePossible, computeAttendancePresentPossible } from "./attendanceRollup.js";
import { applyCompletionAttendanceThreshold } from "./completionProtocol.js";
import { computeDropoutProjections, summarizeReasonShares } from "./dropoutProtocol.js";
import { trackedRosterRoleFilter } from "./traineeRoster.js";
import {
  applyDropoutBufferToCounts,
  contractTargetsByTp,
  effectiveContractNumerator,
  registeredTraineesByTp,
} from "./providerContract.js";
import { enrichDropoutProjectionsWithKpiBuffer } from "./dropoutKpiBuffer.js";
import { collectPooledTierSubjects, subjectsForRateCalculation } from "./verificationRunService.js";

export type VarCounts = { project: number; byTp: Map<string, number> };

const emptyCounts = (): VarCounts => ({ project: 0, byTp: new Map() });

/** Indicators whose monitoring % uses contract target as denominator with capped numerator. */
const CONTRACT_DENOMINATOR_INDICATOR_CODES = new Set([
  "training_completion_rate",
  "trainee_dropout_rate",
  "eligible_enrolled_trainee_rate",
]);

const DROPOUT_INDICATOR_CODE = "trainee_dropout_rate";

type QuerySpec = Record<string, unknown>;
type DropoutReasonShare = { reasonCode: string; count: number; sharePct: number };

function asPolicyObject(spec: QuerySpec): Record<string, unknown> | null {
  const policy = spec.policy;
  if (!policy || typeof policy !== "object") return null;
  return policy as Record<string, unknown>;
}

function resolveOutcomeTypeFromSpec(spec: QuerySpec): string | null {
  if (typeof spec.outcomeType === "string" && spec.outcomeType.trim()) return spec.outcomeType.trim();
  const policy = asPolicyObject(spec);
  if (typeof policy?.completionOutcomeType === "string" && policy.completionOutcomeType.trim()) {
    return policy.completionOutcomeType.trim();
  }
  return null;
}

/** Protocol §4: age 18–29, qualifying education, unemployed/underemployed at enrollment. */
function eligibilityProtocolWhere(): Prisma.TraineeWhereInput {
  /* MySQL: rely on typical utf8mb4_unicode_ci collation for case-insensitive substring match. */
  const educationOr: Prisma.TraineeWhereInput[] = [
    { highestEducation: { contains: "secondary" } },
    { highestEducation: { contains: "grade 12" } },
    { highestEducation: { contains: "g12" } },
    { highestEducation: { contains: "12th" } },
    { highestEducation: { contains: "tvet" } },
    { highestEducation: { contains: "certificate level" } },
    { highestEducation: { contains: "diploma" } },
    { highestEducation: { contains: "university" } },
    { highestEducation: { contains: "college" } },
    { highestEducation: { contains: "bachelor" } },
    { highestEducation: { contains: "above bachelor" } },
    { highestEducation: { contains: "dropout" } },
    { highestEducation: { contains: "high school" } },
  ];
  const employmentOr: Prisma.TraineeWhereInput[] = [
    { employmentStatus: { contains: "not currently working" } },
    { employmentStatus: { contains: "working occasionally" } },
    { employmentStatus: { contains: "fewer hours than desired" } },
    { employmentStatus: { contains: "unemploy" } },
    { employmentStatus: { contains: "underemploy" } },
  ];
  return {
    ageYears: { gte: 18, lte: 29 },
    AND: [{ OR: educationOr }, { OR: employmentOr }],
  };
}

async function countTraineesByTp(projectId: bigint, extraWhere?: Prisma.TraineeWhereInput): Promise<VarCounts> {
  const rows = await prisma.trainee.groupBy({
    by: ["trainingProviderId"],
    where: { projectId, ...extraWhere },
    _count: { _all: true },
  });
  const byTp = new Map<string, number>();
  let project = 0;
  for (const r of rows) {
    const c = r._count._all;
    byTp.set(r.trainingProviderId.toString(), c);
    project += c;
  }
  return { project, byTp };
}

async function countDistinctOutcomeTrainees(projectId: bigint, outcomeType: string): Promise<VarCounts> {
  /** Count outcomes only for tracked roster rows (active + reserve); withdrawn lines are excluded. */
  const rows = await prisma.$queryRaw<{ tp: bigint; c: bigint }[]>`
    SELECT o.training_provider_id AS tp, COUNT(DISTINCT o.trainee_id) AS c
    FROM trainee_outcomes o
    INNER JOIN trainees t ON t.id = o.trainee_id AND t.project_id = o.project_id
    WHERE o.project_id = ${projectId}
      AND o.outcome_type = ${outcomeType}
      AND o.reported_value = 1
      AND t.roster_role IN ('active', 'reserve')
    GROUP BY o.training_provider_id
  `;
  const byTp = new Map<string, number>();
  let project = 0;
  for (const r of rows) {
    const c = Number(r.c);
    byTp.set(r.tp.toString(), c);
    project += c;
  }
  return { project, byTp };
}

async function outcomeParticipationTpIds(projectId: bigint, outcomeType: string): Promise<Set<string>> {
  const rows = await prisma.$queryRaw<{ tp: bigint }[]>`
    SELECT DISTINCT o.training_provider_id AS tp
    FROM trainee_outcomes o
    INNER JOIN trainees t ON t.id = o.trainee_id AND t.project_id = o.project_id
    WHERE o.project_id = ${projectId}
      AND o.outcome_type = ${outcomeType}
      AND t.roster_role IN ('active', 'reserve')
  `;
  return new Set(rows.map((r) => r.tp.toString()));
}

function applyContractCapToCounts(actual: VarCounts, contractByTp: Map<string, number>): VarCounts {
  const byTp = new Map<string, number>();
  let project = 0;
  const keys = new Set([...actual.byTp.keys(), ...contractByTp.keys()]);
  for (const tpId of keys) {
    const contract = contractByTp.get(tpId) ?? 0;
    const raw = actual.byTp.get(tpId) ?? 0;
    const capped = contract > 0 ? effectiveContractNumerator(raw, contract) : 0;
    byTp.set(tpId, capped);
    project += capped;
  }
  return { project, byTp };
}

async function countApprovedActivityByTp(projectId: bigint, activityCode: string): Promise<VarCounts> {
  const rows = await prisma.tpActivitySubmission.groupBy({
    by: ["trainingProviderId"],
    where: {
      projectId,
      status: "approved",
      activity: { code: activityCode, projectId },
    },
    _count: { _all: true },
  });
  const byTp = new Map<string, number>();
  let project = 0;
  for (const r of rows) {
    const has = r._count._all > 0 ? 1 : 0;
    byTp.set(r.trainingProviderId.toString(), has);
    project += has;
  }
  return { project, byTp };
}

async function attendanceToVarCounts(projectId: bigint, mode: "present" | "possible"): Promise<VarCounts> {
  const agg = await computeAttendancePresentPossible(projectId);
  const byTp = new Map<string, number>();
  for (const [tpId, v] of agg.byTp) {
    byTp.set(tpId, mode === "present" ? v.present : v.possible);
  }
  return { project: mode === "present" ? agg.present : agg.possible, byTp };
}

async function countFeedbackByTp(projectId: bigint, mode: "timely_responded" | "total_responded_plus_overdue"): Promise<VarCounts> {
  // COALESCE(first_tp_response_at, first non-public reply) mirrors feedbackMetrics.responseAt()
  // so cases answered before the response timestamp column existed still count — the indicator
  // therefore always agrees with the GRM screens and exports.
  const respondedAt =
    "COALESCE(t.first_tp_response_at, (SELECT MIN(m.created_at) FROM feedback_messages m WHERE m.thread_id = t.id AND m.author_type <> 'public'))";

  const rows =
    mode === "timely_responded"
      ? await prisma.$queryRaw<{ tp: bigint; c: bigint }[]>`
          SELECT t.training_provider_id AS tp, COUNT(*) AS c
          FROM feedback_threads t
          WHERE t.project_id = ${projectId}
            AND ${Prisma.raw(respondedAt)} IS NOT NULL
            AND ${Prisma.raw(respondedAt)} <= t.due_at
          GROUP BY t.training_provider_id
        `
      : await prisma.$queryRaw<{ tp: bigint; c: bigint }[]>`
          SELECT t.training_provider_id AS tp, COUNT(*) AS c
          FROM feedback_threads t
          WHERE t.project_id = ${projectId}
            AND (
              ${Prisma.raw(respondedAt)} IS NOT NULL
              OR (${Prisma.raw(respondedAt)} IS NULL AND t.due_at < NOW())
            )
          GROUP BY t.training_provider_id
        `;
  const byTp = new Map<string, number>();
  let project = 0;
  for (const r of rows) {
    const c = Number(r.c);
    byTp.set(r.tp.toString(), c);
    project += c;
  }
  return { project, byTp };
}

async function attendanceSubmissionCoverageByTp(projectId: bigint): Promise<Map<string, { submitted: number; possible: number }>> {
  const capturePossible = await computeAttendanceCapturePossible(projectId);
  const submittedRows = await prisma.traineeAttendanceDay.groupBy({
    by: ["trainingProviderId"],
    where: { projectId, trainee: { rosterRole: { in: ["active", "reserve"] } } },
    _count: { _all: true },
  });
  const out = new Map<string, { submitted: number; possible: number }>();
  for (const [tpId, slot] of capturePossible.byTp.entries()) {
    out.set(tpId, { submitted: 0, possible: slot.possible });
  }
  for (const r of submittedRows) {
    const tpId = r.trainingProviderId.toString();
    const cur = out.get(tpId) ?? { submitted: 0, possible: 0 };
    cur.submitted = r._count._all;
    out.set(tpId, cur);
  }
  return out;
}

async function resolveVariableCounts(projectId: bigint, variableCode: string | null | undefined): Promise<VarCounts> {
  if (!variableCode) return emptyCounts();
  const v = await prisma.indicatorVariable.findUnique({ where: { code: variableCode } });
  if (!v) return emptyCounts();
  const spec = (v.querySpec ?? {}) as QuerySpec;
  const source = typeof spec.source === "string" ? spec.source : "";

  if (source === "trainees" && (spec.scope === "enrolled" || spec.scope === "registered")) {
    return countTraineesByTp(projectId, { rosterRole: trackedRosterRoleFilter() });
  }
  if (source === "provider_contract") {
    const targets = await contractTargetsByTp(prisma, projectId);
    const byTp = new Map<string, number>();
    let project = 0;
    for (const [tpId, target] of targets) {
      byTp.set(tpId, target);
      project += target;
    }
    return { project, byTp };
  }
  if (source === "trainees_eligibility_protocol" || source === "trainees_eligibility_criteria") {
    return countTraineesByTp(projectId, {
      AND: [{ rosterRole: trackedRosterRoleFilter() }, eligibilityProtocolWhere()],
    });
  }
  /** Completion protocol variable: configured by querySpec policy, not fixed indicator code. */
  if (source === "trainee_completion_protocol") {
    const policy = asPolicyObject(spec);
    const completionOutcomeType = resolveOutcomeTypeFromSpec(spec) ?? "completion";
    const completion = await countDistinctOutcomeTrainees(projectId, completionOutcomeType);
    const attendanceGate = policy?.attendanceGate === true;
    if (!attendanceGate) return completion;
    if (typeof policy?.attendanceThresholdIndicatorCode !== "string" || !policy.attendanceThresholdIndicatorCode.trim()) return emptyCounts();
    const attendanceIndicatorCode = policy.attendanceThresholdIndicatorCode.trim();
    const attendanceIndicator = await prisma.projectIndicator.findFirst({
      where: { projectId, code: attendanceIndicatorCode, isActive: true },
      select: { thresholdValue: true },
    });
    if (attendanceIndicator?.thresholdValue == null) return emptyCounts();
    const threshold = attendanceIndicator?.thresholdValue != null ? Number(attendanceIndicator.thresholdValue) : null;
    const present = await attendanceToVarCounts(projectId, "present");
    const possible = await attendanceToVarCounts(projectId, "possible");
    const gated = applyCompletionAttendanceThreshold(completion, present, possible, threshold);
    const coverage = await attendanceSubmissionCoverageByTp(projectId);
    const byTp = new Map<string, number>();
    let project = 0;
    for (const [tpId, completedCount] of gated.byTp.entries()) {
      const c = coverage.get(tpId);
      const fullySubmitted = !!c && c.possible > 0 && c.submitted >= c.possible;
      const allowed = fullySubmitted ? completedCount : 0;
      byTp.set(tpId, allowed);
      project += allowed;
    }
    return { project, byTp };
  }
  if (source === "trainee_outcomes" && typeof spec.outcomeType === "string") {
    return countDistinctOutcomeTrainees(projectId, spec.outcomeType);
  }
  if (source === "trainee_dropout_protocol") {
    const policy = asPolicyObject(spec);
    const thresholdPct = typeof policy?.thresholdPct === "number" ? Number(policy.thresholdPct) : 80;
    const includeTpReported = policy?.includeTpReported !== false;
    const includeSystemFinal = policy?.includeSystemFinalLowAttendance !== false;
    const projections = await computeDropoutProjections({ projectId });
    const byTp = new Map<string, number>();
    for (const row of projections) {
      const match =
        (includeTpReported && row.tpReportedDropout) ||
        (includeSystemFinal && row.systemDropoutFinal);
      if (!match) continue;
      const tpId = row.trainingProviderId.toString();
      byTp.set(tpId, (byTp.get(tpId) ?? 0) + 1);
    }
    let project = 0;
    for (const c of byTp.values()) project += c;
    if (thresholdPct !== 80) {
      // Placeholder for future configurable thresholds at computation layer.
    }
    return { project, byTp };
  }
  if (source === "weekly_attendance" || source === "session_attendance") {
    if (spec.status === "present") return attendanceToVarCounts(projectId, "present");
    if (spec.scope === "possible") return attendanceToVarCounts(projectId, "possible");
    return emptyCounts();
  }
  if ((source === "activity_submissions" || source === "activity_approval") && typeof spec.activityCode === "string") {
    return countApprovedActivityByTp(projectId, spec.activityCode);
  }
  if (source === "placeholder_zero") {
    return emptyCounts();
  }
  /** @deprecated interim — use grievance_register sources */
  if (source === "public_feedback_timely_resolved") {
    return emptyCounts();
  }
  /** Protocol §19 — wire to grievance register (timely responses vs responded + overdue unresponded). */
  if (source === "grievance_register" && spec.metric === "timely_responded") {
    return countFeedbackByTp(projectId, "timely_responded");
  }
  if (source === "grievance_register" && spec.metric === "total_responded_plus_overdue") {
    return countFeedbackByTp(projectId, "total_responded_plus_overdue");
  }

  return emptyCounts();
}

function mergeTpKeys(a: VarCounts, b?: VarCounts): Set<string> {
  const s = new Set<string>([...a.byTp.keys()]);
  if (b) for (const k of b.byTp.keys()) s.add(k);
  return s;
}

function computeLayer(
  mode: "count" | "percentage",
  num: VarCounts,
  den?: VarCounts,
  aggregateTpFilter?: Set<string> | null,
): { project: number; byTp: Map<string, number> } {
  const byTp = new Map<string, number>();
  if (mode === "count") {
    for (const [id, v] of num.byTp) byTp.set(id, v);
    return { project: num.project, byTp };
  }
  const keys = mergeTpKeys(num, den);
  let pNum = 0;
  let pDen = 0;
  for (const id of keys) {
    const n = num.byTp.get(id) ?? 0;
    const d = den?.byTp.get(id) ?? 0;
    const pct = d > 0 ? Math.round((n / d) * 10000) / 100 : 0;
    byTp.set(id, pct);
    const includeInProject = !aggregateTpFilter || aggregateTpFilter.has(id);
    if (includeInProject) {
      pNum += n;
      pDen += d;
    }
  }
  const project = pDen > 0 ? Math.round((pNum / pDen) * 10000) / 100 : 0;
  return { project, byTp };
}

async function samplingVerifiedCountsByTp(
  projectId: bigint,
  indicatorId: bigint
): Promise<{ numerator: VarCounts; denominator: VarCounts }> {
  const stages = await prisma.projectIndicatorStage.findMany({
    where: { projectId, indicatorId, isActive: true },
    orderBy: [{ isFinalStage: "desc" }, { sortOrder: "desc" }, { id: "desc" }],
    select: { stageKey: true },
  });
  const finalStageKey = stages[0]?.stageKey ?? null;
  const runs = await prisma.verificationSampleRun.findMany({
    where: { projectId, indicatorId, status: "finalized", ...(finalStageKey ? { stageKey: finalStageKey } : {}) },
    orderBy: [{ tier: "desc" }, { drawnAt: "desc" }, { id: "desc" }],
    select: {
      id: true,
      trainingProviderId: true,
      verifiedRatePct: true,
      ciLowerPct: true,
      ciUpperPct: true,
      pathwayLabel: true,
    },
  });
  const latestByTp = new Map<string, (typeof runs)[number]>();
  for (const run of runs) {
    const tp = run.trainingProviderId.toString();
    if (!latestByTp.has(tp)) latestByTp.set(tp, run);
  }

  const numByTp = new Map<string, number>();
  const denByTp = new Map<string, number>();
  let projectNum = 0;
  let projectDen = 0;
  for (const [tp, run] of latestByTp) {
    const pooled = await collectPooledTierSubjects(prisma, run.id);
    const rateSubjects = subjectsForRateCalculation(pooled);
    const num = rateSubjects.filter((s) => s.verificationStatusCode === "V-COMP").length;
    const den = rateSubjects.length;
    denByTp.set(tp, den);
    numByTp.set(tp, num);
    projectNum += num;
    projectDen += den;
  }
  return {
    numerator: { project: projectNum, byTp: numByTp },
    denominator: { project: projectDen, byTp: denByTp },
  };
}

export async function buildIndicatorKpiPayload(projectId: bigint) {
  const reasonSharesByIndicator = new Map<string, DropoutReasonShare[]>();
  const indicators = await prisma.projectIndicator.findMany({
    where: { projectId, isActive: true },
    orderBy: [{ protocolOrder: "asc" }, { code: "asc" }],
  });
  const providers = await prisma.trainingProvider.findMany({
    where: { projectId },
    orderBy: { tpCode: "asc" },
  });

  const codes = new Set<string>();
  for (const i of indicators) {
    for (const c of [
      i.monitoringNumeratorVariable,
      i.monitoringDenominatorVariable,
      i.verificationNumeratorVariable,
      i.verificationDenominatorVariable,
    ]) {
      if (c) codes.add(c);
    }
  }

  const countsMap = new Map<string, VarCounts>();
  const variableSpecs = new Map<string, QuerySpec>();
  for (const c of codes) {
    const row = await prisma.indicatorVariable.findUnique({ where: { code: c }, select: { querySpec: true } });
    variableSpecs.set(c, (row?.querySpec ?? {}) as QuerySpec);
    countsMap.set(c, await resolveVariableCounts(projectId, c));
  }
  const contractByTp = await contractTargetsByTp(prisma, projectId);
  for (const [code, spec] of variableSpecs) {
    if (spec.source === "trainee_completion_protocol") {
      const cur = countsMap.get(code);
      if (cur) countsMap.set(code, applyContractCapToCounts(cur, contractByTp));
    }
  }
  const attendanceCoverage = await attendanceSubmissionCoverageByTp(projectId);

  const kpis: Array<{
    indicatorCode: string;
    tpId: string;
    claimed: number;
    verified: number;
    claimedDenominator?: number;
    verifiedDenominator?: number;
    actualNumerator?: number;
    effectiveNumerator?: number;
    contractTarget?: number;
    registeredTrainees?: number;
    contractConfigured?: boolean;
    claimedCoverageTpCount?: number;
    verifiedCoverageTpCount?: number;
    totalProviders?: number;
    verificationIncomplete?: boolean;
  }> = [];

  const registeredCounts = countsMap.get("registered_trainees") ?? countsMap.get("enrolled_trainees") ?? emptyCounts();

  for (const ind of indicators) {
    const mode = ind.computationMode as "count" | "percentage";
    const monNumActual = countsMap.get(ind.monitoringNumeratorVariable ?? "") ?? emptyCounts();
    let monNum = monNumActual;
    let monDen =
      mode === "percentage" ? countsMap.get(ind.monitoringDenominatorVariable ?? "") ?? emptyCounts() : undefined;
    const usesContractDenominator = CONTRACT_DENOMINATOR_INDICATOR_CODES.has(ind.code);
    if (mode === "percentage" && usesContractDenominator) {
      if (ind.code === DROPOUT_INDICATOR_CODE) {
        monNum = applyDropoutBufferToCounts(monNumActual, registeredCounts, contractByTp);
      } else {
        monNum = applyContractCapToCounts(monNumActual, contractByTp);
      }
      const contractCounts: VarCounts = { project: 0, byTp: new Map() };
      for (const [tpId, target] of contractByTp) {
        contractCounts.byTp.set(tpId, target);
        contractCounts.project += target;
      }
      monDen = contractCounts;
    }
    let verNum = countsMap.get(ind.verificationNumeratorVariable ?? ind.monitoringNumeratorVariable ?? "") ?? emptyCounts();
    let verDen =
      mode === "percentage"
        ? countsMap.get(ind.verificationDenominatorVariable ?? ind.monitoringDenominatorVariable ?? "") ?? emptyCounts()
        : undefined;
    if (ind.verificationMode === "sampling") {
      const sampled = await samplingVerifiedCountsByTp(projectId, ind.id);
      verNum = sampled.numerator;
      verDen = mode === "percentage" ? sampled.denominator : verDen;
    }

    let monitorAggregateFilter: Set<string> | null = null;
    let verifyAggregateFilter: Set<string> | null = null;
    if (mode === "percentage") {
      const monVar = await prisma.indicatorVariable.findUnique({
        where: { code: ind.monitoringNumeratorVariable ?? "" },
        select: { querySpec: true },
      });
      const verVar = await prisma.indicatorVariable.findUnique({
        where: { code: ind.verificationNumeratorVariable ?? ind.monitoringNumeratorVariable ?? "" },
        select: { querySpec: true },
      });
      const monSpec = (monVar?.querySpec ?? {}) as QuerySpec;
      const verSpec = (verVar?.querySpec ?? {}) as QuerySpec;
      if (typeof monSpec.source === "string" && (monSpec.source === "trainee_outcomes" || monSpec.source === "trainee_completion_protocol")) {
        const outcomeType = resolveOutcomeTypeFromSpec(monSpec);
        if (outcomeType) monitorAggregateFilter = await outcomeParticipationTpIds(projectId, outcomeType);
      }
      if (ind.verificationMode === "sampling") {
        verifyAggregateFilter = new Set<string>([...verDen?.byTp.keys() ?? []]);
      } else if (typeof verSpec.source === "string" && (verSpec.source === "trainee_outcomes" || verSpec.source === "trainee_completion_protocol")) {
        const outcomeType = resolveOutcomeTypeFromSpec(verSpec);
        if (outcomeType) verifyAggregateFilter = await outcomeParticipationTpIds(projectId, outcomeType);
      }
    }

    const mon = computeLayer(mode, monNum, monDen, monitorAggregateFilter);
    const ver = computeLayer(mode, verNum, verDen, verifyAggregateFilter);
    const claimedCoverageTpCount =
      mode === "percentage"
        ? [...(monitorAggregateFilter ?? new Set<string>(monDen?.byTp.keys() ?? []))].filter((tpId) => (monDen?.byTp.get(tpId) ?? 0) > 0).length
        : 0;
    const verifiedCoverageTpCount =
      mode === "percentage"
        ? [...(verifyAggregateFilter ?? new Set<string>(verDen?.byTp.keys() ?? []))].filter((tpId) => (verDen?.byTp.get(tpId) ?? 0) > 0).length
        : 0;
    const verificationIncomplete =
      mode === "percentage" &&
      ind.verificationMode !== "none" &&
      claimedCoverageTpCount > 0 &&
      verifiedCoverageTpCount < claimedCoverageTpCount;
    const usesCompletionProtocol =
      [ind.monitoringNumeratorVariable, ind.verificationNumeratorVariable]
        .filter((v): v is string => Boolean(v))
        .some((v) => variableSpecs.get(v)?.source === "trainee_completion_protocol");
    const completionBlockedTpCount = usesCompletionProtocol
      ? [...attendanceCoverage.values()].filter((v) => v.possible > 0 && v.submitted < v.possible).length
      : 0;
    const usesDropoutProtocol =
      [ind.monitoringNumeratorVariable, ind.verificationNumeratorVariable]
        .filter((v): v is string => Boolean(v))
        .some((v) => variableSpecs.get(v)?.source === "trainee_dropout_protocol");
    if (usesDropoutProtocol) {
      const projectionRaw = await computeDropoutProjections({ projectId });
      const registeredByTp = await registeredTraineesByTp(prisma, projectId);
      const projection = enrichDropoutProjectionsWithKpiBuffer(projectionRaw, contractByTp, registeredByTp);
      reasonSharesByIndicator.set(ind.code, summarizeReasonShares(projection, { forKpiRate: true }).shares);
    }

    for (const p of providers) {
      const id = p.id.toString();
      const claimedDenominator = mode === "percentage" ? (monDen?.byTp.get(id) ?? 0) : undefined;
      const verifiedDenominator = mode === "percentage" ? (verDen?.byTp.get(id) ?? 0) : undefined;
      const contractTarget = contractByTp.get(id);
      kpis.push({
        indicatorCode: ind.code,
        tpId: id,
        claimed: mon.byTp.get(id) ?? 0,
        verified: ver.byTp.get(id) ?? 0,
        ...(mode === "percentage"
          ? {
              claimedDenominator,
              verifiedDenominator,
              actualNumerator: monNumActual.byTp.get(id) ?? 0,
              effectiveNumerator: monNum.byTp.get(id) ?? 0,
              contractTarget: contractTarget ?? undefined,
              registeredTrainees: registeredCounts.byTp.get(id) ?? 0,
              contractConfigured: contractTarget != null && contractTarget > 0,
            }
          : {}),
      });
    }
    kpis.push({
      indicatorCode: ind.code,
      tpId: "PROJECT",
      claimed: mon.project,
      verified: ver.project,
      ...(mode === "percentage"
        ? {
            claimedDenominator: monDen?.project ?? 0,
            verifiedDenominator: verDen?.project ?? 0,
            claimedCoverageTpCount,
            verifiedCoverageTpCount,
            totalProviders: providers.length,
            verificationIncomplete,
            ...(usesCompletionProtocol
              ? {
                  completionBlockedByAttendance: completionBlockedTpCount > 0,
                  completionBlockedTpCount,
                }
              : {}),
            ...(usesDropoutProtocol
              ? {
                  dropoutReasonShares: reasonSharesByIndicator.get(ind.code) ?? [],
                }
              : {}),
          }
        : {}),
    });
  }

  return {
    computedAt: new Date().toISOString(),
    indicators: indicators.map((i) => ({
      id: i.id.toString(),
      code: i.code,
      name: i.name,
      description: i.description,
      unit: i.unit,
      computationMode: i.computationMode,
      claimMode: i.claimMode,
      verificationMode: i.verificationMode,
      thresholdValue: i.thresholdValue != null ? Number(i.thresholdValue) : null,
    })),
    providers: providers.map((p) => ({ id: p.id.toString(), tpCode: p.tpCode, name: p.name })),
    kpis,
  };
}
