import { describe, expect, it } from "../test/testHarness";

import {
  TEXT_INPUT_CREDITS_PER_MILLION,
  TEXT_OUTPUT_CREDITS_PER_MILLION,
  estimateTextTokenCredits,
  formatTextTokenCreditRule,
  getTaskTimeoutPolicy,
  isTaskLocallyTimedOut,
} from "./taskLifecycle";

describe("taskLifecycle", () => {
  it("keeps fallback text token billing at 1 CNY to 100 credits", () => {
    expect(TEXT_INPUT_CREDITS_PER_MILLION).toBe(200);
    expect(TEXT_OUTPUT_CREDITS_PER_MILLION).toBe(500);
    expect(
      estimateTextTokenCredits({
        promptTokens: 1_000_000,
        completionTokens: 1_000_000,
      }),
    ).toBe(700);
  });

  it("estimates text billing from dynamic server pricing rates", () => {
    expect(
      estimateTextTokenCredits(
        {
          promptTokens: 1_000_000,
          completionTokens: 1_000_000,
        },
        {
          inputCreditsPerMillion: 2_700,
          outputCreditsPerMillion: 10_800,
          source: "server",
          modelKey: "gpt-4o",
        },
      ),
    ).toBe(13_500);
  });

  it("ignores negative token counts when estimating text billing", () => {
    expect(
      estimateTextTokenCredits({
        promptTokens: -100,
        completionTokens: 500_000,
      }),
    ).toBe(250);
  });

  it("formats text billing rules from the selected rate", () => {
    expect(
      formatTextTokenCreditRule({
        inputCreditsPerMillion: 2_700,
        outputCreditsPerMillion: 10_800,
      }),
    ).toBe(
      "输入 Token 每百万 2,700 积分，输出 Token 每百万 10,800 积分，实际以服务端结算为准。",
    );
  });

  it("marks unstarted tasks locally timed out after submit timeout", () => {
    const policy = getTaskTimeoutPolicy({ kind: "image" });

    expect(
      isTaskLocallyTimedOut({
        startedAt: 1_000,
        lastProgressAt: 1_000,
        now: 1_000 + policy.submitTimeoutMs,
        policy,
        progress: 0,
      }),
    ).toBe("no_progress");
  });

  it("marks running tasks locally timed out when progress stops", () => {
    const policy = getTaskTimeoutPolicy({ kind: "video", model: "wan2.7-i2v" });

    expect(
      isTaskLocallyTimedOut({
        startedAt: 1_000,
        lastProgressAt: 2_000,
        now: 2_000 + policy.noProgressTimeoutMs,
        policy,
        progress: 40,
      }),
    ).toBe("no_progress");
  });
});
