/**
 * Anlik kopya (snapshot) / geri al / yeniden yap: proje klasorunun gizli bir git deposunda (kullanicinin
 * kendi .git'ine DOKUNMADAN, ~/.sera/snapshots/<klasor-ozeti>) agac ozetleri tutulur.
 *
 * Ilke: geri alma yalniz o turun degistirdigi dosyalara dokunur; tur bittikten sonra kullanicinin kendisinin
 * degistirdigi dosya ATLANIR (ustune yazilmaz) ve raporlanir. Proje .gitignore'u gecerlidir.
 */

import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve, sep } from "node:path";

export interface RestoreReport {
	restored: string[];
	deleted: string[];
	/** Turdan sonra kullanicinin degistirdigi, bu yuzden dokunulmayan dosyalar. */
	skipped: string[];
}

const DEFAULT_EXCLUDES = ["node_modules/", ".sera/snapshots/", "*.log"];

function run(args: string[], env: NodeJS.ProcessEnv, cwd: string): Promise<{ code: number; out: Buffer }> {
	return new Promise((res, rej) => {
		const p = spawn("git", args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
		const chunks: Buffer[] = [];
		p.stdout.on("data", (c: Buffer) => chunks.push(c));
		p.stderr.on("data", () => {});
		p.on("error", rej);
		p.on("close", (code) => res({ code: code ?? 1, out: Buffer.concat(chunks) }));
	});
}

export class SnapshotStore {
	readonly gitDir: string;
	readonly workTree: string;
	private ready: Promise<void> | undefined;

	constructor(workTree: string, baseDir = join(homedir(), ".sera", "snapshots")) {
		this.workTree = resolve(workTree);
		const key = createHash("sha1").update(this.workTree.toLowerCase()).digest("hex").slice(0, 16);
		this.gitDir = join(baseDir, key);
	}

	private env(): NodeJS.ProcessEnv {
		return { ...process.env, GIT_DIR: this.gitDir, GIT_WORK_TREE: this.workTree, GIT_INDEX_FILE: undefined };
	}

	private async git(args: string[]): Promise<Buffer> {
		const r = await run(
			["-c", "core.autocrlf=false", "-c", "core.safecrlf=false", "-c", "core.quotepath=false", ...args],
			this.env(),
			this.workTree,
		);
		if (r.code !== 0) throw new Error(`git ${args[0]} basarisiz (${r.code})`);
		return r.out;
	}

	private init(): Promise<void> {
		this.ready ??= (async () => {
			if (!existsSync(join(this.gitDir, "HEAD"))) {
				mkdirSync(this.gitDir, { recursive: true });
				await this.git(["init", "-q"]);
				mkdirSync(join(this.gitDir, "info"), { recursive: true });
				writeFileSync(join(this.gitDir, "info", "exclude"), `${DEFAULT_EXCLUDES.join("\n")}\n`);
			}
		})();
		return this.ready;
	}

	/** Calisma klasorunun su anki halini kaydeder; agac ozetini doner. */
	async track(): Promise<string> {
		await this.init();
		await this.git(["add", "-A", "--", "."]);
		return (await this.git(["write-tree"])).toString().trim();
	}

	/** iki agac arasinda degisen dosyalar (goreli, / ayracli). */
	async changed(from: string, to: string): Promise<string[]> {
		if (from === to) return [];
		const out = (await this.git(["diff-tree", "-r", "--name-only", "--no-renames", "-z", from, to])).toString();
		return out.split("\0").filter(Boolean);
	}

	private async blobIn(tree: string, path: string): Promise<string | undefined> {
		const r = await run(["rev-parse", "-q", "--verify", `${tree}:${path}`], this.env(), this.workTree);
		return r.code === 0 ? r.out.toString().trim() : undefined;
	}

	private async blobNow(path: string): Promise<string | undefined> {
		const abs = this.abs(path);
		if (!existsSync(abs)) return undefined;
		return (await this.git(["hash-object", "--", abs])).toString().trim();
	}

	private abs(path: string): string {
		const abs = resolve(this.workTree, path);
		if (abs !== this.workTree && !abs.startsWith(this.workTree + sep)) throw new Error(`klasor disi yol: ${path}`);
		return abs;
	}

	/**
	 * `to` halindeki dosyalari `from` haline dondurur (geri al: from=tur oncesi, to=tur sonu; yeniden yap: tersi).
	 * Simdiki icerigi `to` ile ayni olmayan dosya kullanicinin sonradan degistirdigidir: atlanir.
	 */
	async restore(from: string, to: string): Promise<RestoreReport> {
		await this.init();
		const rep: RestoreReport = { restored: [], deleted: [], skipped: [] };
		for (const path of await this.changed(from, to)) {
			const [want, after, now] = await Promise.all([
				this.blobIn(from, path),
				this.blobIn(to, path),
				this.blobNow(path),
			]);
			if (now !== after) {
				rep.skipped.push(path);
				continue;
			}
			const abs = this.abs(path);
			if (!want) {
				rmSync(abs, { force: true });
				rep.deleted.push(path);
				continue;
			}
			mkdirSync(dirname(abs), { recursive: true });
			writeFileSync(abs, await this.git(["cat-file", "blob", want]));
			rep.restored.push(path);
		}
		return rep;
	}
}

/** Sade Turkce ozet (kullaniciya/modele). */
export function restoreSummary(rep: RestoreReport, verb: "geri alindi" | "yeniden uygulandi"): string {
	const n = rep.restored.length + rep.deleted.length;
	const parts = [n ? `${n} dosya ${verb}.` : "Degisen dosya yok."];
	if (rep.skipped.length)
		parts.push(
			`Sonradan senin degistirdigin ${rep.skipped.length} dosyaya dokunulmadi: ${rep.skipped.slice(0, 5).join(", ")}${rep.skipped.length > 5 ? " ..." : ""}`,
		);
	return parts.join(" ");
}
