import type { ReviewSampleRecord } from "../types/global";

export type ReviewSampleAnalysis = {
  total: number;
  withParsed: number;
  averageConfidence: number;
  weakFields: Array<{ field: string; count: number; average: number }>;
  reasons: Array<{ reason: string; count: number }>;
  latestSavedAt?: string;
};

type ParsedLike = {
  confidence?: unknown;
  fields?: Record<string, { confidence?: unknown } | undefined>;
};

export function analyzeReviewSamples(samples: ReviewSampleRecord[]): ReviewSampleAnalysis {
  const reasonCounts = new Map<string, number>();
  const fieldCounts = new Map<string, { count: number; sum: number }>();
  let confidenceSum = 0;
  let parsedCount = 0;
  let latestSavedAt = "";

  for (const entry of samples) {
    if (entry.savedAt && (!latestSavedAt || entry.savedAt > latestSavedAt)) latestSavedAt = entry.savedAt;

    const reason = normalizeReason(entry.sample?.reason);
    reasonCounts.set(reason, (reasonCounts.get(reason) ?? 0) + 1);

    const parsed = entry.sample?.parsed as ParsedLike | undefined;
    if (!parsed || typeof parsed !== "object") continue;

    const confidence = typeof parsed.confidence === "number" ? parsed.confidence : null;
    if (confidence !== null) {
      confidenceSum += confidence;
      parsedCount++;
    }

    for (const [field, value] of Object.entries(parsed.fields ?? {})) {
      const fieldConfidence = value && typeof value.confidence === "number" ? value.confidence : null;
      if (fieldConfidence === null || fieldConfidence >= 70) continue;
      const current = fieldCounts.get(field) ?? { count: 0, sum: 0 };
      current.count++;
      current.sum += fieldConfidence;
      fieldCounts.set(field, current);
    }
  }

  return {
    total: samples.length,
    withParsed: parsedCount,
    averageConfidence: parsedCount > 0 ? Math.round(confidenceSum / parsedCount) : 0,
    weakFields: [...fieldCounts.entries()]
      .map(([field, value]) => ({ field, count: value.count, average: Math.round(value.sum / value.count) }))
      .sort((a, b) => b.count - a.count || a.average - b.average || a.field.localeCompare(b.field)),
    reasons: [...reasonCounts.entries()]
      .map(([reason, count]) => ({ reason, count }))
      .sort((a, b) => b.count - a.count || a.reason.localeCompare(b.reason)),
    latestSavedAt: latestSavedAt || undefined,
  };
}

function normalizeReason(reason: string | undefined) {
  if (!reason) return "unknown";
  return reason
    .replace(/^automatic:/, "")
    .replace(/^manual:/, "")
    .replace(/^probe:/, "")
    .replace(/:p\d+.*$/, "")
    .replace(/:preflight.*$/, "")
    .trim() || "unknown";
}
