import { isPlainObject } from "es-toolkit";

import type { RawTargetConfig } from "../../types";

import { compactExpect, normalizeContent, normalizeKeyed, normalizeValue } from "../../expect/normalize";

export function normalizeTargetExpect(target: RawTargetConfig): RawTargetConfig {
  if (target.expect === undefined || !isPlainObject(target.expect)) return target;
  const raw = target.expect as Record<string, unknown>;
  return {
    ...target,
    expect: compactExpect(raw, {
      durationMs: normalizeValue(raw["durationMs"]),
      finishReason: normalizeValue(raw["finishReason"]),
      headers: normalizeKeyed(raw["headers"]),
      output: normalizeContent(raw["output"]),
      rawFinishReason: normalizeValue(raw["rawFinishReason"]),
      status: raw["status"],
      stream: isPlainObject(raw["stream"])
        ? compactExpect(raw["stream"] as Record<string, unknown>, {
            completed: (raw["stream"] as Record<string, unknown>)["completed"],
            firstTokenMs: normalizeValue((raw["stream"] as Record<string, unknown>)["firstTokenMs"]),
          })
        : raw["stream"],
      usage: isPlainObject(raw["usage"])
        ? compactExpect(raw["usage"] as Record<string, unknown>, {
            inputTokens: normalizeValue((raw["usage"] as Record<string, unknown>)["inputTokens"]),
            outputTokens: normalizeValue((raw["usage"] as Record<string, unknown>)["outputTokens"]),
            totalTokens: normalizeValue((raw["usage"] as Record<string, unknown>)["totalTokens"]),
          })
        : raw["usage"],
    }),
  };
}
