/**
 * Tests for `deficitPegState` / `isDeficitPegged` — B1 honesty-guard (#1958/#1959).
 *
 * The §22 deficit_index is clamped to [−1, 1] and saturates at balance_ratio=0.5;
 * when supply massively dwarfs demand (ratio ≪ 0.5 на всех горизонтах) every
 * horizon clamps to exactly −1.00 (зеркально +1.00 для острого дефицита). Showing
 * «−1.00 ×4» reads as broken / falsely precise, so Section6Forecast detects the
 * saturated state once and renders a honest «на пределе» plaque over 6.1 / 6.2.
 *
 * The state is pegged only when EVERY present row is saturated AND same-signed —
 * a single non-pegged / opposite-sign row means there IS differentiation.
 */
import { describe, expect, it } from "vitest";

import { deficitPegState, isDeficitPegged } from "../forecast-helpers";

function rows(...values: (number | null)[]) {
  return values.map(
    (deficit_index) =>
      ({ deficit_index }) as {
        deficit_index: number;
      },
  );
}

describe("isDeficitPegged — B1 saturation threshold (#1958/#1959)", () => {
  it("is pegged at ±1.00 and within eps of the edge", () => {
    expect(isDeficitPegged(-1)).toBe(true);
    expect(isDeficitPegged(1)).toBe(true);
    expect(isDeficitPegged(-0.99)).toBe(true);
    expect(isDeficitPegged(0.995)).toBe(true);
  });

  it("is NOT pegged below the threshold (real differentiation)", () => {
    expect(isDeficitPegged(-0.98)).toBe(false);
    expect(isDeficitPegged(0.5)).toBe(false);
    expect(isDeficitPegged(0)).toBe(false);
  });
});

describe("deficitPegState — across horizons (#1958/#1959)", () => {
  it("pegs at −1.00 on all horizons (затоварка) → sign −1", () => {
    expect(deficitPegState(rows(-1, -1, -1, -1))).toEqual({
      pegged: true,
      sign: -1,
    });
  });

  it("pegs at +1.00 on all horizons (острый дефицит) → sign +1", () => {
    expect(deficitPegState(rows(1, 1, 1, 1))).toEqual({
      pegged: true,
      sign: 1,
    });
  });

  it("does NOT peg when a row is mid-range (signal differentiates)", () => {
    expect(deficitPegState(rows(-1, -1, -0.6, -1))).toEqual({
      pegged: false,
      sign: null,
    });
  });

  it("does NOT peg when saturated rows have opposite signs", () => {
    expect(deficitPegState(rows(-1, 1))).toEqual({
      pegged: false,
      sign: null,
    });
  });

  it("ignores null deficit_index and pegs on present saturated rows only", () => {
    expect(deficitPegState(rows(null, -1, null, -1))).toEqual({
      pegged: true,
      sign: -1,
    });
  });

  it("is not pegged when no rows carry a deficit_index", () => {
    expect(deficitPegState(rows(null, null))).toEqual({
      pegged: false,
      sign: null,
    });
    expect(deficitPegState([])).toEqual({ pegged: false, sign: null });
  });
});
