import { deriveToolCallSummary, formatToolBodyHtml } from "../../utils/toolCall";
import styles from "./ToolCallBlock.module.css";

interface ToolCallBlockProps {
	content: string;
	forceOpen?: boolean;
}

function parseToolCallContent(content: string): {
	title: string;
	body: string;
	status: "pending" | "success" | "error";
} {
	const trimmed = content.trimStart();
	let status: "pending" | "success" | "error" = "pending";
	let rest = trimmed;
	if (trimmed.startsWith("✅")) {
		status = "success";
		rest = trimmed.slice(1).trimStart();
	} else if (trimmed.startsWith("❌")) {
		status = "error";
		rest = trimmed.slice(1).trimStart();
	} else if (trimmed.startsWith("🔧")) {
		status = "pending";
		rest = trimmed.slice(2).trimStart();
	}

	const lines = rest.split("\n");
	const title = lines[0]?.trim() || "tool";
	const body = lines.slice(1).join("\n").trim();
	return { title, body, status };
}

export function ToolCallBlock({ content, forceOpen }: ToolCallBlockProps) {
	const { title, body, status } = parseToolCallContent(content);
	const hasDiff =
		body.includes("\n+") || body.includes("\n-") || body.startsWith("+") || body.startsWith("-");
	const statusLabel = status === "success" ? "完成" : status === "error" ? "失败" : "执行中";

	return (
		<details
			className={`${styles.block} ${styles[status]}`}
			open={forceOpen || status === "pending"}
		>
			<summary className={styles.summary}>
				<span className={styles.toolName}>{title.split("(")[0] || deriveToolCallSummary(content)}</span>
				<span className={styles.status}>{statusLabel}</span>
			</summary>
			{(body || content !== title) && (
				<div className={styles.detail}>
					{title.includes("(") ? <div className={styles.args}>{title}</div> : null}
					{hasDiff ? (
						<pre
							className={styles.detailPre}
							dangerouslySetInnerHTML={{ __html: formatToolBodyHtml(body || content) }}
						/>
					) : (
						<pre className={styles.detailPre}>{body || content}</pre>
					)}
				</div>
			)}
		</details>
	);
}
