'use strict';

// 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 renderErrorLine(detail) {
  return renderStatusLine("\uC624\uB958", detail);
}
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()
      };
    }
  );
}

// src/platform/ai-services/internal/codex-stream-json-output-processor.ts
function normalizeKind(value) {
  return value.replace(/[^a-z]/gi, "").toLowerCase();
}
function extractCodexAssistantText(value) {
  const record = asRecord(value);
  if (!record) {
    return "";
  }
  if (typeof record.delta === "string") {
    return record.delta;
  }
  if (typeof record.text === "string") {
    return record.text;
  }
  if (typeof record.content === "string") {
    return record.content;
  }
  const contentText = extractTextFromContentBlocks(record.content);
  if (contentText) {
    return contentText;
  }
  return extractCodexAssistantText(record.message) || extractCodexAssistantText(record.item);
}
function renderCodexItemLine(eventType, itemType, item) {
  if (itemType === "reasoning") {
    return "";
  }
  if (itemType === "commandexecution") {
    return renderStatusLine(eventType === "item.completed" ? "\uBA85\uB839 \uC644\uB8CC" : "\uBA85\uB839", summarizeValue(item) || "\uC178 \uBA85\uB839\uC744 \uC2E4\uD589\uD588\uC2B5\uB2C8\uB2E4.");
  }
  if (itemType === "filechange") {
    return renderStatusLine("\uD30C\uC77C \uBCC0\uACBD", summarizeValue(item.files) || summarizeValue(item) || "\uD30C\uC77C\uC744 \uC218\uC815\uD588\uC2B5\uB2C8\uB2E4.");
  }
  if (itemType === "mcptoolcall") {
    return renderStatusLine("MCP", summarizeValue(item) || "MCP \uB3C4\uAD6C\uB97C \uD638\uCD9C\uD588\uC2B5\uB2C8\uB2E4.");
  }
  if (itemType === "plan") {
    return renderStatusLine("\uACC4\uD68D", summarizeValue(item) || "\uC791\uC5C5 \uACC4\uD68D\uC744 \uC5C5\uB370\uC774\uD2B8\uD588\uC2B5\uB2C8\uB2E4.");
  }
  if (itemType === "websearch") {
    return renderStatusLine("\uAC80\uC0C9", summarizeValue(item) || "\uC6F9 \uAC80\uC0C9\uC744 \uC2E4\uD589\uD588\uC2B5\uB2C8\uB2E4.");
  }
  return "";
}
function createCodexStreamJsonOutputProcessor() {
  let accumulatedText = "";
  let fallbackStdout = "";
  return createLineBufferedProcessor(
    (line) => {
      const trimmedLine = line.trim();
      if (!trimmedLine) {
        return {};
      }
      try {
        const parsed = JSON.parse(trimmedLine);
        const eventType = typeof parsed.type === "string" ? parsed.type : "";
        if (eventType === "thread.started") {
          return { streamFragment: renderStatusLine("\uC138\uC158", "Codex \uC791\uC5C5\uC744 \uC2DC\uC791\uD588\uC2B5\uB2C8\uB2E4.") };
        }
        if (eventType === "turn.started") {
          return { streamFragment: renderStatusLine("\uC9C4\uD589", "\uC751\uB2F5 \uC0DD\uC131\uC744 \uC2DC\uC791\uD588\uC2B5\uB2C8\uB2E4.") };
        }
        if (eventType === "turn.failed" || eventType === "error") {
          return {
            streamFragment: renderErrorLine(summarizeValue(parsed.message) || summarizeValue(parsed.error) || "Codex \uC2E4\uD589\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.")
          };
        }
        if (eventType === "item.started" || eventType === "item.completed") {
          const item = asRecord(parsed.item);
          const itemType = item ? normalizeKind(pickFirstString(item, ["type", "item_type"])) : "";
          if (itemType === "agentmessage") {
            const text = extractCodexAssistantText(item);
            if (!text) {
              return {};
            }
            accumulatedText += text;
            return {
              stdoutFragment: text,
              streamFragment: text
            };
          }
          return {
            streamFragment: item ? renderCodexItemLine(eventType, itemType, item) : ""
          };
        }
        return {};
      } catch {
        fallbackStdout += `${line}
`;
        return {
          stdoutFragment: `${line}
`,
          streamFragment: `${line}
`
        };
      }
    },
    () => ({
      stdoutFragment: accumulatedText || fallbackStdout.trimEnd()
    })
  );
}

// src/platform/ai-services/internal/gemini-stream-json-output-processor.ts
function extractGeminiAgentText(value) {
  const parsed = asRecord(value);
  const role = typeof parsed?.role === "string" ? parsed.role : "";
  if (parsed?.type !== "message" || !["agent", "assistant", "model"].includes(role)) {
    return "";
  }
  if (typeof parsed.delta === "string") {
    return parsed.delta;
  }
  if (typeof parsed.text === "string") {
    return parsed.text;
  }
  if (typeof parsed.content === "string") {
    return parsed.content;
  }
  return extractTextFromContentBlocks(parsed.content);
}
function createGeminiStreamJsonOutputProcessor() {
  let accumulatedText = "";
  let fallbackStdout = "";
  return createLineBufferedProcessor(
    (line) => {
      const trimmedLine = line.trim();
      if (!trimmedLine) {
        return {};
      }
      try {
        const parsed = JSON.parse(trimmedLine);
        if (parsed.type === "message") {
          const text = extractGeminiAgentText(parsed);
          if (!text) {
            return {};
          }
          accumulatedText += text;
          return {
            stdoutFragment: text,
            streamFragment: text
          };
        }
        if (parsed.type === "tool_use") {
          return {
            streamFragment: renderToolUseLine(String(parsed.tool_name || parsed.name || "Gemini \uB3C4\uAD6C"), parsed.parameters || parsed.input)
          };
        }
        if (parsed.type === "tool_result") {
          const success = parsed.status !== "error";
          const detail = summarizeValue(parsed.output) || summarizeValue(parsed.error);
          return {
            streamFragment: renderToolResultLine(String(parsed.tool_id || parsed.tool_name || "Gemini \uB3C4\uAD6C"), detail, success)
          };
        }
        if (parsed.type === "error") {
          return {
            streamFragment: renderErrorLine(summarizeValue(parsed.message) || "Gemini \uC2E4\uD589 \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.")
          };
        }
        return {};
      } catch {
        fallbackStdout += `${line}
`;
        return {
          stdoutFragment: `${line}
`,
          streamFragment: `${line}
`
        };
      }
    },
    () => ({
      stdoutFragment: accumulatedText || fallbackStdout.trimEnd()
    })
  );
}

// src/platform/ai-services/internal/output-processors.ts
function createPlainTextOutputProcessor() {
  return {
    processStdoutChunk(chunk) {
      return {
        stdoutFragment: chunk,
        streamFragment: chunk
      };
    },
    finalize() {
      return {};
    }
  };
}
function createServiceOutputProcessor(protocol = "plain-text") {
  if (protocol === "claude-stream-json") {
    return createClaudeStreamJsonOutputProcessor();
  }
  if (protocol === "codex-stream-json") {
    return createCodexStreamJsonOutputProcessor();
  }
  if (protocol === "gemini-stream-json") {
    return createGeminiStreamJsonOutputProcessor();
  }
  return createPlainTextOutputProcessor();
}

exports.createServiceOutputProcessor = createServiceOutputProcessor;
