import { describe, expect, it } from "vitest";

import {
  initialReviewState,
  parseReviewBlock,
  reduceReview,
  type ReviewSseEvent,
} from "./sse";

describe("parseReviewBlock — style (C4 扩 T4.2)", () => {
  it("parses a style frame carrying the text anchor", () => {
    const evt = parseReviewBlock(
      'event:style\ndata:{"score":87,"segments":[{"idx":3,"text":"原文锚","score":60,"label":"口语化"}]}',
    );
    expect(evt).toEqual({
      event: "style",
      data: {
        score: 87,
        segments: [{ idx: 3, text: "原文锚", score: 60, label: "口语化" }],
      },
    });
  });

  it("defaults missing segment text to null when parsing", () => {
    const evt = parseReviewBlock(
      'event:style\ndata:{"score":87,"segments":[{"idx":3,"score":60}]}',
    );
    expect(evt).toEqual({
      event: "style",
      data: {
        score: 87,
        segments: [{ idx: 3, text: null, score: 60, label: null }],
      },
    });
  });

  it("parses a degrade态 style frame (无指纹 score=100/空段)", () => {
    expect(parseReviewBlock('event:style\ndata:{"score":100,"segments":[]}')).toEqual(
      { event: "style", data: { score: 100, segments: [] } },
    );
  });
});

describe("reduceReview — style (replace-style like pace)", () => {
  it("sets style report and marks reviewing", () => {
    const evt: ReviewSseEvent = {
      event: "style",
      data: {
        score: 80,
        segments: [{ idx: 1, text: "原文锚", score: 50, label: "突兀" }],
      },
    };
    const out = reduceReview(initialReviewState, evt);
    expect(out.phase).toBe("reviewing");
    expect(out.style).toEqual({
      score: 80,
      segments: [{ idx: 1, text: "原文锚", score: 50, label: "突兀" }],
    });
  });

  it("replaces (not accumulates) the style report and defaults text/label", () => {
    const first = reduceReview(initialReviewState, {
      event: "style",
      data: { score: 70, segments: [{ idx: 0, score: 40 }] },
    });
    const second = reduceReview(first, {
      event: "style",
      data: { score: 95, segments: [] },
    });
    expect(first.style?.segments[0]).toEqual({
      idx: 0,
      text: "",
      score: 40,
      label: null,
    });
    expect(second.style).toEqual({ score: 95, segments: [] });
  });

  it("leaves style untouched on a section event", () => {
    const seeded = reduceReview(initialReviewState, {
      event: "style",
      data: { score: 88, segments: [] },
    });
    const out = reduceReview(seeded, {
      event: "section",
      data: { name: "style", status: "done" },
    });
    expect(out.style).toEqual({ score: 88, segments: [] });
    expect(out.sections).toEqual([{ name: "style", status: "done" }]);
  });
});
