<script setup lang="ts">
import MarkdownIt from "markdown-it";
import { computed } from "vue";

const props = defineProps<{
  content: string;
  reasoning?: string;
  showReasoning?: boolean;
  streaming?: boolean;
}>();

const markdown = new MarkdownIt({ breaks: true, html: false, linkify: true });
const parsed = computed(() => splitReasoning(props.content));
const answer = computed(() => parsed.value.answer.replace(/^\s+/, ""));
const reasoning = computed(() => props.reasoning || parsed.value.reasoning);
const renderedContent = computed(() => answer.value.trim() ? markdown.render(normalizeStandaloneHeadings(answer.value)) : "");

function normalizeStandaloneHeadings(content: string) {
  return content.replace(/^([ \t]*)\*\*(.+)\*\*[ \t]*$/gm, (line, indent: string, title: string) => {
    const normalizedTitle = title.trim();
    if (!normalizedTitle || normalizedTitle.length > 48 || normalizedTitle.includes("**")) return line;
    return `${indent}### ${normalizedTitle}`;
  });
}

function splitReasoning(content: string) {
  const lower = content.toLowerCase();
  let answer = "";
  let reasoning = "";
  let cursor = 0;
  let depth = 0;
  while (cursor < content.length) {
    const tagStart = content.indexOf("<", cursor);
    if (tagStart === -1) {
      if (depth) reasoning += content.slice(cursor);
      else answer += content.slice(cursor);
      break;
    }
    const text = content.slice(cursor, tagStart);
    if (depth) reasoning += text;
    else answer += text;
    const tail = lower.slice(tagStart);
    const openTag = tail.match(/^<think(?:\s[^>]*)?>/);
    if (openTag) {
      depth += 1;
      cursor = tagStart + openTag[0].length;
      continue;
    }
    const closeTag = tail.match(/^<\/think\s*>/);
    if (closeTag) {
      depth = Math.max(0, depth - 1);
      cursor = tagStart + closeTag[0].length;
      continue;
    }
    if ("<think".startsWith(tail) || "</think>".startsWith(tail)) break;
    if (depth) reasoning += "<";
    else answer += "<";
    cursor = tagStart + 1;
  }
  return { answer, reasoning };
}
</script>

<template>
  <details v-if="showReasoning && reasoning.trim()" class="agent-reasoning-panel" :open="streaming">
    <summary>思考过程</summary>
    <div class="agent-reasoning-content">{{ reasoning }}</div>
  </details>
  <div v-if="renderedContent" class="agent-preview-markdown" v-html="renderedContent"></div>
  <div v-else-if="streaming" class="agent-preview-generation-state">
    <span></span><span></span><span></span>
    思考中
  </div>
</template>
