import { mkdir, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { ReviewContext } from "./git.ts";

function slug(input: string): string {
	return input
		.toLowerCase()
		.replace(/[^a-z0-9._-]+/g, "-")
		.replace(/^-+|-+$/g, "") || "unknown";
}

function timestampUtc(): string {
	const iso = new Date().toISOString();
	return iso.replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
}

export async function writeReviewHtml(context: ReviewContext, html: string): Promise<string> {
	const outputDir = path.join(os.tmpdir(), "pi-show-diff");
	await mkdir(outputDir, { recursive: true });

	const fileName = `${slug(context.repoName)}--${slug(context.branch)}--vs-${slug(context.base)}--${timestampUtc()}.html`;
	const outputPath = path.join(outputDir, fileName);

	await writeFile(outputPath, html, "utf8");
	return outputPath;
}
