import { describe, expect, it } from "vitest";
import { analyzeReviewSamples } from "./reviewSampleAnalysis";
import type { ReviewSampleRecord } from "../types/global";

describe("analyzeReviewSamples", () => {
  it("summarizes weak fields, reasons, and average confidence", () => {
    const samples: ReviewSampleRecord[] = [
      sample("2026-01-01T00:00:00.000Z", "automatic:low-total-confidence-72:p1:r0c5", 72, {
        name: 78,
        substats: 0,
        equipped: 45,
      }),
      sample("2026-01-02T00:00:00.000Z", "manual:low-field-mainStat-substats", 86, {
        mainStat: 62,
        substats: 55,
      }),
      { savedAt: "2026-01-03T00:00:00.000Z", sample: { reason: "probe:no-detail-change:r1c1" } },
    ];

    const analysis = analyzeReviewSamples(samples);

    expect(analysis.total).toBe(3);
    expect(analysis.withParsed).toBe(2);
    expect(analysis.averageConfidence).toBe(79);
    expect(analysis.latestSavedAt).toBe("2026-01-03T00:00:00.000Z");
    expect(analysis.reasons.map((entry) => entry.reason)).toEqual([
      "low-field-mainStat-substats",
      "low-total-confidence-72",
      "no-detail-change:r1c1",
    ]);
    expect(analysis.weakFields[0]).toMatchObject({ field: "substats", count: 2, average: 28 });
    expect(analysis.weakFields).toContainEqual({ field: "equipped", count: 1, average: 45 });
  });
});

function sample(savedAt: string, reason: string, confidence: number, fields: Record<string, number>): ReviewSampleRecord {
  return {
    savedAt,
    sample: {
      reason,
      parsed: {
        confidence,
        fields: Object.fromEntries(
          Object.entries(fields).map(([key, fieldConfidence]) => [key, { confidence: fieldConfidence }]),
        ),
      },
    },
  };
}
