
// ---- Helpers: pretty print nested JSON as YAML-like (braceless, unquoted) ----
const MAX_REPARSE_DEPTH = 2;

function tryParseJson(input: string): unknown {
  try {
    return JSON.parse(input);
  } catch {
    return input;
  }
}

function parsePossiblyNestedJson(raw: string): unknown {
  let current: unknown = raw;
  for (let i = 0; i < MAX_REPARSE_DEPTH; i++) {
    if (typeof current === 'string') {
      const trimmed = current.trim();
      if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
        current = tryParseJson(trimmed);
        continue;
      }
    }
    break;
  }
  return current;
}

function indentLines(text: string, indent: string): string {
  return text.split('\n').map((line) => indent + line).join('\n');
}

function looksLikeStructuredText(s: string): boolean {
  const t = s.trim();
  // 具有成对的大括号，或常见的 Rust/reqwest 错误标识，判定为可结构化的调试输出
  return (t.includes('{') && t.includes('}')) || t.includes('DynamicTransportError') || t.includes('reqwest::Error');
}

function prettyFormatByBraces(input: string): string {
  let out = '';
  let indentLevel = 0;
  const indentUnit = '  ';
  let inString = false;
  let stringQuote = '';
  for (let i = 0; i < input.length; i++) {
    const ch = input[i]!;
    const prev = i > 0 ? input[i - 1]! : '';
    if ((ch === '"' || ch === "'") && prev !== '\\') {
      if (!inString) {
        inString = true;
        stringQuote = ch;
      } else if (stringQuote === ch) {
        inString = false;
      }
      out += ch;
      continue;
    }
    if (inString) {
      out += ch;
      continue;
    }
    if (ch === '{' || ch === '[' || ch === '(') {
      indentLevel += 1;
      out += ch + '\n' + indentUnit.repeat(indentLevel);
      continue;
    }
    if (ch === '}' || ch === ']' || ch === ')') {
      indentLevel = Math.max(0, indentLevel - 1);
      out += '\n' + indentUnit.repeat(indentLevel) + ch;
      continue;
    }
    if (ch === ',') {
      out += ch + '\n' + indentUnit.repeat(indentLevel);
      continue;
    }
    if (ch === ':') {
      out += ch + ' ';
      continue;
    }
    out += ch;
  }
  return out;
}

export function toPseudoYaml(value: unknown, indent: string = ''): string {
  const nextIndent = indent + '  ';
  if (value === null || value === undefined) {
    return `${indent}null`;
  }
  const t = typeof value;
  if (t === 'string' || t === 'number' || t === 'boolean') {
    const s = String(value);
    const shouldPretty = looksLikeStructuredText(s) || s.includes('\n');
    if (shouldPretty) {
      const pretty = looksLikeStructuredText(s) ? prettyFormatByBraces(s) : s;
      return `${indent}|-\n${indentLines(pretty, nextIndent)}`;
    }
    return `${indent}${s}`;
  }
  if (Array.isArray(value)) {
    if (value.length === 0) return `${indent}[]`;
    return value.map((item) => {
      const rendered = toPseudoYaml(item, nextIndent);
      const lines = rendered.split('\n');
      if (lines.length === 1) {
        return `${indent}- ${lines[0].trimStart()}`;
      }
      return `${indent}- ${lines[0].trimStart()}\n${lines.slice(1).map((l) => indent + '  ' + l.trimStart()).join('\n')}`;
    }).join('\n');
  }
  if (typeof value === 'object') {
    const obj = value as Record<string, unknown>;
    const keys = Object.keys(obj);
    if (keys.length === 0) return `${indent}{}`;
    return keys.map((k) => {
      const rendered = toPseudoYaml(obj[k], nextIndent);
      const lines = rendered.split('\n');
      if (lines.length === 1) {
        return `${indent}${k}: ${lines[0].trimStart()}`;
      }
      return `${indent}${k}:\n${lines.map((l) => l).join('\n')}`;
    }).join('\n');
  }
  // fallback
  return `${indent}${String(value)}`;
}

export function formatDetailsToYaml(details: string): string {
  const parsed = parsePossiblyNestedJson(details);
  if (typeof parsed === 'string') {
    // 尝试再次解析（有些场景内层 message 也是 JSON 串）
    const again = parsePossiblyNestedJson(parsed);
    if (typeof again === 'string') {
      return toPseudoYaml(again);
    }
    return toPseudoYaml(again);
  }
  return toPseudoYaml(parsed);
}

