import type { ToolResultMessage } from "@jaeswift/jae-ai";
import { html } from "lit";
import { FileText } from "lucide";
import { registerToolRenderer, renderHeader } from "../renderer-registry.js";
import type { ToolRenderer, ToolRenderResult } from "../types.js";

export class DiffRenderer implements ToolRenderer {
	render(params: any, result: ToolResultMessage | undefined, isStreaming?: boolean): ToolRenderResult {
		const rawContent = result?.content;
		const resultText = Array.isArray(rawContent)
			? rawContent
					.filter((c: any) => c.type === "text")
					.map((c: any) => c.text)
					.join("\n")
			: typeof rawContent === "string"
				? rawContent
				: "";
		const diff = params?.diff || params?.patch || resultText || "";
		const filename = params?.file || params?.filename || "";
		const state = result ? (result.isError ? "error" : "complete") : "inprogress";
		const label = filename ? "Diff: " + filename : "File Diff";

		const lines = diff.split("\n");

		return {
			content: html`
        <div class="space-y-3">
          ${renderHeader(state, FileText, label)}
          ${
					diff
						? html`
            <div class="overflow-auto max-h-96 rounded-lg border border-border">
              <pre class="text-xs font-mono p-4">${lines.map((line: string) => {
						let cls = "block";
						if (line.startsWith("+") && !line.startsWith("+++"))
							cls = "text-green-500 bg-green-500/10 block px-1";
						else if (line.startsWith("-") && !line.startsWith("---"))
							cls = "text-red-500 bg-red-500/10 block px-1";
						else if (line.startsWith("@@")) cls = "text-blue-400 block px-1";
						else if (line.startsWith("diff ") || line.startsWith("index "))
							cls = "text-muted-foreground block px-1";
						else cls = "block px-1";
						return html`<span class=${cls}>${line}</span>
`;
					})}</pre>
            </div>
          `
						: ""
				}
        </div>
      `,
			isCustom: false,
		};
	}
}

registerToolRenderer("diff", new DiffRenderer());
registerToolRenderer("patch", new DiffRenderer());
