import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeHighlight from "rehype-highlight";

function formatAnswer(answer) {
  if (!answer) return "";

  const trimmed = answer.trim();
  if (trimmed.startsWith("```") && trimmed.endsWith("```")) {
    return answer;
  }

  const lines = answer.split("\n");
  if (lines.length <= 1) {
    return answer;
  }

  const pythonIndicators = [
    /def\s+\w+\(/,
    /import\s+\w+/,
    /from\s+\w+\s+import/,
    /print\(/,
    /input\(/,
    /for\s+\w+\s+in\s+/,
    /if\s+__name__\s*==/,
    /all\(/,
    /any\(/,
    /list\(map\(/,
    /\[.*\]/,
    /arr\s*=/,
    /result\s*=/
  ];

  const hasPython = pythonIndicators.some(regex => regex.test(answer));
  const hasIndentation = lines.some(line => /^\s{2,}/.test(line) || /^\t/.test(line));

  if (hasPython || hasIndentation) {
    return "```python\n" + answer + "\n```";
  }

  return answer;
}

export function AnswerRenderer({ answer }) {
  return (
    <div className="answer-body">
      <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
        {formatAnswer(answer)}
      </ReactMarkdown>
    </div>
  );
}
