import {
  BUILT_IN_TOOL_NAMES
} from "./chunk-7XQLG5P2.js";
import {
  init_ids,
  newId
} from "./chunk-F4WUVOLE.js";

// src/backends/claude/translator.ts
init_ids();
var BUILT_IN_SET = new Set(BUILT_IN_TOOL_NAMES);
function createClaudeTranslator(opts) {
  const toolClass = /* @__PURE__ */ new Map();
  const toolSpan = /* @__PURE__ */ new Map();
  const toolMeta = /* @__PURE__ */ new Map();
  let claudeSessionId = null;
  let sawInit = false;
  let sawCustom = false;
  let turnResult = null;
  function classify(name) {
    if (BUILT_IN_SET.has(name)) return "builtin";
    if (name.startsWith("mcp__")) return "mcp";
    if (opts.customToolNames.has(name)) return "custom";
    return "builtin";
  }
  function translate(raw) {
    const out = [];
    const type = String(raw.type ?? "");
    if (type === "system") {
      const subtype = raw.subtype;
      if (subtype === "init") {
        if (typeof raw.session_id === "string") {
          claudeSessionId = raw.session_id;
        }
        if (!sawInit && opts.isFirstTurn) {
          sawInit = true;
        }
        sawInit = true;
      }
      return out;
    }
    if (type === "assistant") {
      const msg = raw.message ?? {};
      const blocks = msg.content ?? [];
      for (const block of blocks) {
        if (block.type === "text" && typeof block.text === "string") {
          out.push({
            type: "agent.message",
            payload: {
              content: [{ type: "text", text: block.text }]
            }
          });
        } else if (block.type === "thinking" && typeof block.thinking === "string") {
          out.push({
            type: "agent.thinking",
            payload: {
              content: [{ type: "thinking", thinking: block.thinking }]
            }
          });
        } else if (block.type === "tool_use" && block.id && block.name) {
          const cls = classify(block.name);
          toolClass.set(block.id, cls);
          let toolSpanId;
          if (opts.turnSpanId) {
            toolSpanId = newId("span");
            toolSpan.set(block.id, toolSpanId);
            toolMeta.set(block.id, { name: block.name, startMs: Date.now() });
            out.push({
              type: "span.tool_call_start",
              payload: {
                tool_use_id: block.id,
                name: block.name,
                tool_class: cls
              },
              spanId: toolSpanId,
              parentSpanId: opts.turnSpanId
            });
          }
          if (cls === "custom") {
            sawCustom = true;
            out.push({
              type: "agent.custom_tool_use",
              payload: {
                tool_use_id: block.id,
                name: block.name,
                input: block.input ?? {}
              },
              ...toolSpanId ? { spanId: toolSpanId, parentSpanId: opts.turnSpanId } : {}
            });
          } else if (cls === "mcp") {
            const parts = block.name.split("__");
            const serverName = parts[1] ?? "unknown";
            const toolName = parts.slice(2).join("__") || block.name;
            out.push({
              type: "agent.mcp_tool_use",
              payload: {
                tool_use_id: block.id,
                server_name: serverName,
                tool_name: toolName,
                input: block.input ?? {}
              },
              ...toolSpanId ? { spanId: toolSpanId, parentSpanId: opts.turnSpanId } : {}
            });
          } else {
            out.push({
              type: "agent.tool_use",
              payload: {
                tool_use_id: block.id,
                name: block.name,
                input: block.input ?? {}
              },
              ...toolSpanId ? { spanId: toolSpanId, parentSpanId: opts.turnSpanId } : {}
            });
          }
        }
      }
      return out;
    }
    if (type === "user") {
      const msg = raw.message ?? {};
      const blocks = msg.content ?? [];
      for (const block of blocks) {
        if (block.type === "tool_result" && block.tool_use_id) {
          const cls = toolClass.get(block.tool_use_id);
          if (cls === "custom") continue;
          const eventType = cls === "mcp" ? "agent.mcp_tool_result" : "agent.tool_result";
          const toolSpanId = toolSpan.get(block.tool_use_id);
          const meta = toolMeta.get(block.tool_use_id);
          out.push({
            type: eventType,
            payload: {
              tool_use_id: block.tool_use_id,
              content: block.content ?? null,
              is_error: block.is_error ?? false
            },
            ...toolSpanId ? { spanId: toolSpanId, parentSpanId: opts.turnSpanId } : {}
          });
          if (toolSpanId && opts.turnSpanId) {
            const durationMs = meta ? Date.now() - meta.startMs : null;
            out.push({
              type: "span.tool_call_end",
              payload: {
                tool_use_id: block.tool_use_id,
                name: meta?.name ?? null,
                tool_class: cls ?? "builtin",
                status: block.is_error ? "error" : "ok",
                duration_ms: durationMs
              },
              spanId: toolSpanId,
              parentSpanId: opts.turnSpanId
            });
            toolSpan.delete(block.tool_use_id);
            toolMeta.delete(block.tool_use_id);
          }
        }
      }
      return out;
    }
    if (type === "result") {
      const subtype = String(raw.subtype ?? "success");
      const usageRaw = raw.usage ?? {};
      const usage = {
        input_tokens: usageRaw.input_tokens ?? 0,
        output_tokens: usageRaw.output_tokens ?? 0,
        cache_read_input_tokens: usageRaw.cache_read_input_tokens ?? 0,
        cache_creation_input_tokens: usageRaw.cache_creation_input_tokens ?? 0,
        cost_usd: raw.total_cost_usd ?? 0
      };
      let stopReason;
      if (sawCustom) stopReason = "custom_tool_call";
      else if (subtype === "error_max_turns") stopReason = "max_turns";
      else if (subtype === "error_during_execution") stopReason = "error";
      else stopReason = "end_turn";
      turnResult = {
        stopReason,
        usage,
        num_turns: raw.num_turns ?? 1
      };
      return out;
    }
    return out;
  }
  return {
    translate,
    getBackendSessionId: () => claudeSessionId,
    getTurnResult: () => turnResult,
    sawCustomToolUse: () => sawCustom
  };
}

export {
  createClaudeTranslator
};
