export type ToolTagCall = {
  name: string;
  rawInput: string;
};

export type ParsedToolTagMessage = {
  text: string;
  calls: ToolTagCall[];
};

const isValidTagName = (name: string) => /^[a-zA-Z][a-zA-Z0-9_]*$/.test(name);

// v1：简单、可预测的“类 XML 标签”协议：
// - 工具调用：<tool_name>{...json...}</tool_name>
// - 工具结果（回喂模型）：<tool_result tool="tool_name">{...json...}</tool_result>
//
// 解析策略：
// - 只解析白名单工具名（避免误把普通 HTML 当工具）
// - 不做嵌套/属性解析（足够支撑 v1）
export const parseToolTagCalls = (input: string, allowedToolNames: Set<string>): ParsedToolTagMessage => {
  const s = String(input ?? "");
  if (!s) return { text: "", calls: [] };

  const calls: ToolTagCall[] = [];
  let outText = "";

  let i = 0;
  while (i < s.length) {
    const lt = s.indexOf("<", i);
    if (lt === -1) {
      outText += s.slice(i);
      break;
    }
    outText += s.slice(i, lt);

    const gt = s.indexOf(">", lt + 1);
    if (gt === -1) {
      outText += s.slice(lt);
      break;
    }

    const tagName = s.slice(lt + 1, gt).trim();
    if (!isValidTagName(tagName) || !allowedToolNames.has(tagName)) {
      outText += s.slice(lt, gt + 1);
      i = gt + 1;
      continue;
    }

    const close = `</${tagName}>`;
    const closeIdx = s.indexOf(close, gt + 1);
    if (closeIdx === -1) {
      outText += s.slice(lt, gt + 1);
      i = gt + 1;
      continue;
    }

    const rawInput = s.slice(gt + 1, closeIdx).trim();
    calls.push({ name: tagName, rawInput });
    i = closeIdx + close.length;
  }

  return { text: outText.trim(), calls };
};

export const formatToolResultTag = (toolName: string, jsonText: string) => {
  const safeName = isValidTagName(toolName) ? toolName : "unknown";
  const body = String(jsonText ?? "").trim();
  return `<tool_result tool="${safeName}">${body}</tool_result>`;
};

