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

exports.createGeminiStreamJsonOutputProcessor = createGeminiStreamJsonOutputProcessor;
