// src/platform/ai-services/internal/structured-output-helpers.ts
function asRecord(value) {
  return value && typeof value === "object" ? value : void 0;
}
function normalizeWhitespace(text) {
  return text.replace(/\s+/g, " ").trim();
}
function truncateText(text, max = 120) {
  return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;
}
function pickFirstString(value, keys) {
  for (const key of keys) {
    if (typeof value[key] === "string") {
      return value[key];
    }
  }
  return "";
}
function formatPathForDisplay(rawPath) {
  const normalized = rawPath.replace(/\\/g, "/");
  const segments = normalized.split("/").filter(Boolean);
  if (segments.length <= 2) {
    return normalized;
  }
  return `.../${segments.slice(-2).join("/")}`;
}
function summarizeValue(value) {
  if (typeof value === "string") {
    return truncateText(normalizeWhitespace(value));
  }
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  if (Array.isArray(value)) {
    const items = value.map((item) => summarizeValue(item)).filter(Boolean);
    if (items.length === 0) {
      return "";
    }
    const head = items.slice(0, 2).join(", ");
    return items.length > 2 ? `${head} \uC678 ${items.length - 2}\uAC1C` : head;
  }
  const record = asRecord(value);
  if (!record) {
    return "";
  }
  const pathValue = pickFirstString(record, ["file_path", "filePath", "path", "target_path", "uri"]);
  if (pathValue) {
    return formatPathForDisplay(pathValue);
  }
  const commandValue = pickFirstString(record, ["command", "commandLine", "command_line", "cmd"]);
  if (commandValue) {
    return truncateText(normalizeWhitespace(commandValue));
  }
  const textValue = pickFirstString(record, ["q", "query", "prompt", "text", "description", "label", "name"]);
  if (textValue) {
    return truncateText(normalizeWhitespace(textValue));
  }
  return "";
}
function renderStatusLine(label, detail) {
  return detail ? `[${label}] ${detail}
` : `[${label}]
`;
}
function renderToolUseLine(name, input) {
  const detail = summarizeValue(input);
  return renderStatusLine("\uB3C4\uAD6C", detail ? `${name} ${detail}` : name);
}
function renderToolResultLine(label, detail, success = true) {
  const status = success ? "\uC644\uB8CC" : "\uC2E4\uD328";
  return renderStatusLine("\uB3C4\uAD6C \uACB0\uACFC", detail ? `${label} ${status}: ${detail}` : `${label} ${status}`);
}
function extractTextFromContentBlocks(content) {
  if (!Array.isArray(content)) {
    return "";
  }
  return content.flatMap((block) => {
    if (typeof block === "string") {
      return [block];
    }
    const normalized = asRecord(block);
    if (!normalized) {
      return [];
    }
    if (typeof normalized.text === "string") {
      return [normalized.text];
    }
    if (typeof normalized.content === "string") {
      return [normalized.content];
    }
    return [];
  }).join("");
}
function createLineBufferedProcessor(processLine, finalizeState) {
  let incompleteLineBuffer = "";
  return {
    processStdoutChunk(chunk) {
      incompleteLineBuffer += chunk;
      let stdoutFragment = "";
      let streamFragment = "";
      let lineBreakIndex = incompleteLineBuffer.indexOf("\n");
      while (lineBreakIndex >= 0) {
        const currentLine = incompleteLineBuffer.slice(0, lineBreakIndex);
        const processed = processLine(currentLine);
        stdoutFragment += processed.stdoutFragment || "";
        streamFragment += processed.streamFragment || "";
        incompleteLineBuffer = incompleteLineBuffer.slice(lineBreakIndex + 1);
        lineBreakIndex = incompleteLineBuffer.indexOf("\n");
      }
      return {
        stdoutFragment,
        streamFragment
      };
    },
    finalize() {
      let stdoutFragment = "";
      let streamFragment = "";
      if (incompleteLineBuffer.trim()) {
        const processed = processLine(incompleteLineBuffer);
        stdoutFragment += processed.stdoutFragment || "";
        streamFragment += processed.streamFragment || "";
      }
      incompleteLineBuffer = "";
      const finalized = finalizeState();
      return {
        stdoutFragment: finalized.stdoutFragment ?? stdoutFragment,
        streamFragment: `${streamFragment}${finalized.streamFragment || ""}` || void 0
      };
    }
  };
}

// src/platform/ai-services/internal/claude-stream-json-output-processor.ts
function extractClaudeAssistantText(value) {
  const message = asRecord(asRecord(value)?.message);
  return extractTextFromContentBlocks(message?.content).replace(/\n{3,}/g, "\n\n");
}
function extractClaudeAssistantMessageId(value) {
  const message = asRecord(asRecord(value)?.message);
  if (typeof message?.id === "string") {
    return message.id;
  }
  return typeof asRecord(value)?.uuid === "string" ? asRecord(value)?.uuid : void 0;
}
function extractClaudeToolResultSummary(value) {
  const record = asRecord(value);
  const file = asRecord(record?.file);
  if (file && typeof file.filePath === "string") {
    const lineCount = typeof file.numLines === "number" ? `${file.numLines}\uC904` : "";
    return [formatPathForDisplay(file.filePath), lineCount].filter(Boolean).join(" ");
  }
  return summarizeValue(record?.content) || summarizeValue(record?.message) || summarizeValue(value);
}
function createClaudeStreamJsonOutputProcessor() {
  const assistantMessageOrder = [];
  const assistantMessageTexts = /* @__PURE__ */ new Map();
  const seenToolUseIds = /* @__PURE__ */ new Set();
  let anonymousAssistantIndex = 0;
  let fallbackStdout = "";
  let finalResultText = "";
  return createLineBufferedProcessor(
    (line) => {
      const trimmedLine = line.trim();
      if (!trimmedLine) {
        return {};
      }
      try {
        const parsed = JSON.parse(trimmedLine);
        if (parsed.type === "assistant") {
          const messageText = extractClaudeAssistantText(parsed);
          const messageId = extractClaudeAssistantMessageId(parsed) || `anonymous-assistant-${anonymousAssistantIndex++}`;
          if (messageText) {
            if (!assistantMessageTexts.has(messageId)) {
              assistantMessageOrder.push(messageId);
            }
            assistantMessageTexts.set(messageId, messageText);
          }
          const content = asRecord(parsed.message)?.content;
          const toolUseBlocks = Array.isArray(content) ? content.map((block) => asRecord(block)).filter(Boolean) : [];
          const streamFragment = toolUseBlocks.filter((block) => block?.type === "tool_use" && typeof block.id === "string" && !seenToolUseIds.has(block.id)).map((block) => {
            seenToolUseIds.add(block.id);
            return renderToolUseLine(String(block.name || "Claude \uB3C4\uAD6C"), block.input);
          }).join("");
          return { streamFragment };
        }
        if (parsed.type === "user") {
          return {
            streamFragment: renderToolResultLine("Claude \uB3C4\uAD6C", extractClaudeToolResultSummary(parsed.tool_use_result))
          };
        }
        if (parsed.type === "stream_event") {
          const event = asRecord(parsed.event);
          const delta = asRecord(event?.delta);
          if (event?.type === "content_block_start") {
            const contentBlock = asRecord(event.content_block);
            if (contentBlock?.type === "tool_use" && typeof contentBlock.id === "string" && !seenToolUseIds.has(contentBlock.id)) {
              seenToolUseIds.add(contentBlock.id);
              return {
                streamFragment: renderToolUseLine(String(contentBlock.name || "Claude \uB3C4\uAD6C"), contentBlock.input)
              };
            }
          }
          if (event?.type === "content_block_delta" && delta?.type === "text_delta" && typeof delta.text === "string") {
            return {
              stdoutFragment: delta.text,
              streamFragment: delta.text
            };
          }
          return {};
        }
        if (parsed.type === "result" && typeof parsed.result === "string") {
          finalResultText = parsed.result;
        } else if (parsed.type === "result" && typeof parsed.error === "string" && !finalResultText) {
          finalResultText = parsed.error;
        }
        return {};
      } catch {
        fallbackStdout += `${line}
`;
        return {
          stdoutFragment: `${line}
`,
          streamFragment: `${line}
`
        };
      }
    },
    () => {
      const assistantStdout = assistantMessageOrder.map((messageId) => assistantMessageTexts.get(messageId) || "").filter(Boolean).join("\n\n");
      return {
        stdoutFragment: finalResultText || assistantStdout || fallbackStdout.trimEnd()
      };
    }
  );
}

export { createClaudeStreamJsonOutputProcessor };
