import assert from "node:assert/strict";
import { test } from "node:test";

import {
  buildGoogleFailurePayloadFields,
  classifyGoogleFailureCategory,
  extractGoogleFailureDetails,
  isGoogleResultNoDetail,
  rebuildGoogleFailureForSessionEnd,
} from "../google-failure-detector.ts";

test("isGoogleResultNoDetail: raw only status error", () => {
  assert.equal(isGoogleResultNoDetail({ status: "error" }), true);
  assert.equal(
    isGoogleResultNoDetail({ status: "error", message: "quota exceeded" }),
    false,
  );
});

test("classifyGoogleFailureCategory: google_tool_error from failed tools", () => {
  assert.equal(
    classifyGoogleFailureCategory({
      status: "failed",
      failed_tool_names: ["write_report"],
    }),
    "google_tool_error",
  );
});

test("classifyGoogleFailureCategory: google_settled_no_detail", () => {
  assert.equal(
    classifyGoogleFailureCategory({
      status: "error",
      tool_call_count: 2,
      duration_ms: 20000,
      raw: { status: "error" },
    }),
    "google_settled_no_detail",
  );
});

test("classifyGoogleFailureCategory: rate_limited", () => {
  assert.equal(
    classifyGoogleFailureCategory({
      status: "error",
      error_message: "HTTP 429 quota exceeded",
    }),
    "rate_limited",
  );
});

test("buildGoogleFailurePayloadFields: includes runtime_provider google", () => {
  const fields = buildGoogleFailurePayloadFields({
    status: "failed",
    tool_call_count: 1,
    duration_ms: 5000,
    raw: { status: "error", message: "Tool call failed for [write_report]" },
    failed_tool_names: ["write_report"],
    session_id: "session-test",
    task_id: "TASK-20260606-006",
  });
  assert.equal(fields.runtime_provider, "google");
  assert.equal(fields.failure_category, "google_tool_error");
  assert.ok(Array.isArray(fields.suggested_actions));
});

test("rebuildGoogleFailureForSessionEnd: no_detail from runDetail", () => {
  const rebuilt = rebuildGoogleFailureForSessionEnd({
    runDetail: {
      sdk_no_detail: true,
      runtime_provider: "google",
      failure_category: "google_settled_no_detail",
    },
    duration_ms: 12000,
    tool_call_count: 2,
    task_id: "TASK-20260606-006",
    status: "failed",
  });
  assert.equal(rebuilt.runtime_provider, "google");
  assert.equal(rebuilt.failure_category, "google_settled_no_detail");
  assert.equal(rebuilt.sdk_no_detail, true);
});

test("extractGoogleFailureDetails: api error message", () => {
  const detail = extractGoogleFailureDetails({
    status: "error",
    message: "Generative Language API error",
    code: "INVALID_ARGUMENT",
  });
  assert.equal(detail.sdk_error_message, "Generative Language API error");
  assert.equal(detail.sdk_error_code, "INVALID_ARGUMENT");
});
