import assert from "node:assert/strict";
import test from "node:test";
import {
  aggregateLocationScore,
  buildEvaluationScore,
  parseRecentWeightsCsv,
  signalFromScore,
  trendDirectionFromDelta,
} from "@/lib/experienciometro/scoring";

test("evaluation scoring computes category and total weighted results", () => {
  const result = buildEvaluationScore([
    {
      categoryId: "a",
      categoryKey: "a",
      categoryName: "A",
      categoryWeight: 2,
      itemId: "a1",
      itemWeight: 1,
      score: 3,
    },
    {
      categoryId: "a",
      categoryKey: "a",
      categoryName: "A",
      categoryWeight: 2,
      itemId: "a2",
      itemWeight: 1,
      score: 2,
    },
    {
      categoryId: "b",
      categoryKey: "b",
      categoryName: "B",
      categoryWeight: 1,
      itemId: "b1",
      itemWeight: 1,
      score: 1,
    },
  ]);

  assert.equal(result.categories.length, 2);
  assert.equal(result.totalScoreRaw, 2);
  assert.equal(result.totalScorePct, 66.7);
});

test("location aggregation supports weighted recent fallback", () => {
  const score = aggregateLocationScore({
    scoresDesc: [80, 60, 40],
    aggregationMode: "weighted_recent",
    recentWindow: 3,
    recentWeights: [0.5, 0.3, 0.2],
  });

  assert.equal(score, 66);
});

test("location aggregation supports moving and full average", () => {
  assert.equal(
    aggregateLocationScore({
      scoresDesc: [90, 60, 30],
      aggregationMode: "moving_average",
      recentWindow: 2,
      recentWeights: [],
    }),
    75
  );

  assert.equal(
    aggregateLocationScore({
      scoresDesc: [90, 60, 30],
      aggregationMode: "full_average",
      recentWindow: 2,
      recentWeights: [],
    }),
    60
  );
});

test("signal and trend helper behavior", () => {
  assert.equal(signalFromScore(86, { greenThreshold: 85, yellowThreshold: 70 }), "green");
  assert.equal(signalFromScore(80, { greenThreshold: 85, yellowThreshold: 70 }), "yellow");
  assert.equal(signalFromScore(60, { greenThreshold: 85, yellowThreshold: 70 }), "red");

  assert.equal(trendDirectionFromDelta(2), "up");
  assert.equal(trendDirectionFromDelta(-1), "down");
  assert.equal(trendDirectionFromDelta(0.1), "flat");
});

test("parseRecentWeightsCsv filters invalid values", () => {
  assert.deepEqual(parseRecentWeightsCsv("0.5, 0.3, foo, -1, 0.2"), [0.5, 0.3, 0.2]);
});
