'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 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/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()
    })
  );
}

exports.createCodexStreamJsonOutputProcessor = createCodexStreamJsonOutputProcessor;
