/**
 * GitHub ajani icin kalici arka plan izleyici: Sera kapaliyken de calisir.
 *  - Windows: Gorev Zamanlayici (schtasks, kullanici duzeyi, YONETICI GEREKTIRMEZ), oturum aciksa her 5 dk.
 *    Pencere cakmasin diye wscript //B ile gizli calisan kucuk .vbs sarmalayici.
 *  - macOS: launchd kullanici ajani (~/Library/LaunchAgents). Linux: kullanici crontab'i (isaretli satir).
 * Tek ornek kilidi + gunluk butce tavani github-agent.ts'te (acquireLock / dailyMaxUsd); durdur = gorevi siler.
 * Tum dis cagrilar enjekte edilen `Exec` ile yapilir: testte sahte exec, gercek makinede gercek.
 */
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";

export type Exec = (
	cmd: string,
	args: string[],
	opts?: { input?: string; timeoutMs?: number },
) => Promise<{ code: number; stdout: string; stderr: string }>;

export const TASK_NAME = "SeraGithubAjan";
export const LAUNCHD_LABEL = "com.sera.github-ajan";
export const CRON_MARK = "# sera-github-ajan";

export interface ScheduleSpec {
	platform: NodeJS.Platform;
	/** Ajan evi (config.json, tick.vbs/tick.log burada). */
	home: string;
	node: string;
	/** tick betigi (github-tick.ts) mutlak yolu. */
	tickScript: string;
	everyMin?: number;
	/** Test icin: LaunchAgents/ dizinini degistirir. */
	launchAgentsDir?: string;
}

const q = (s: string) => `"${s.replace(/"/g, '""')}"`;

export function tickCommandLine(s: ScheduleSpec): string {
	return `${q(s.node)} ${q(s.tickScript)}`;
}

/** Windows: gizli calistirici .vbs icerigi. */
export function vbsContent(s: ScheduleSpec): string {
	const cmd = `${q(s.node)} ${q(s.tickScript)}`.replace(/"/g, '""');
	return `CreateObject("WScript.Shell").Run "${cmd}", 0, True\r\n`;
}

export function windowsCreateArgs(s: ScheduleSpec): string[] {
	const vbs = join(s.home, "tick.vbs");
	const tr = `wscript.exe //B //Nologo ${q(vbs)}`;
	return ["/Create", "/TN", TASK_NAME, "/SC", "MINUTE", "/MO", String(s.everyMin ?? 5), "/TR", tr, "/F"];
}

export function plistContent(s: ScheduleSpec): string {
	const secs = (s.everyMin ?? 5) * 60;
	return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>${LAUNCHD_LABEL}</string>
<key>ProgramArguments</key><array><string>${s.node}</string><string>${s.tickScript}</string></array>
<key>StartInterval</key><integer>${secs}</integer>
<key>RunAtLoad</key><true/>
<key>StandardErrorPath</key><string>${join(s.home, "tick.log")}</string>
</dict></plist>
`;
}

export function cronLine(s: ScheduleSpec): string {
	return `*/${s.everyMin ?? 5} * * * * ${q(s.node)} ${q(s.tickScript)} >> ${q(join(s.home, "tick.log"))} 2>&1 ${CRON_MARK}`;
}

const plistPath = (s: ScheduleSpec) =>
	join(s.launchAgentsDir ?? join(homedir(), "Library", "LaunchAgents"), `${LAUNCHD_LABEL}.plist`);

export interface ScheduleResult {
	ok: boolean;
	detail: string;
}

export async function installSchedule(exec: Exec, s: ScheduleSpec): Promise<ScheduleResult> {
	mkdirSync(s.home, { recursive: true });
	if (s.platform === "win32") {
		writeFileSync(join(s.home, "tick.vbs"), vbsContent(s));
		const r = await exec("schtasks", windowsCreateArgs(s), { timeoutMs: 30_000 });
		return { ok: r.code === 0, detail: (r.stdout + r.stderr).trim().slice(0, 300) };
	}
	if (s.platform === "darwin") {
		const p = plistPath(s);
		mkdirSync(join(p, ".."), { recursive: true });
		writeFileSync(p, plistContent(s));
		await exec("launchctl", ["unload", p], { timeoutMs: 15_000 });
		const r = await exec("launchctl", ["load", "-w", p], { timeoutMs: 15_000 });
		return { ok: r.code === 0, detail: (r.stdout + r.stderr).trim().slice(0, 300) };
	}
	const cur = await exec("crontab", ["-l"], { timeoutMs: 15_000 });
	const keep = (cur.code === 0 ? cur.stdout : "").split("\n").filter((l) => l.trim() && !l.includes(CRON_MARK));
	const r = await exec("crontab", ["-"], { input: `${[...keep, cronLine(s)].join("\n")}\n`, timeoutMs: 15_000 });
	return { ok: r.code === 0, detail: (r.stdout + r.stderr).trim().slice(0, 300) };
}

export async function removeSchedule(
	exec: Exec,
	s: Pick<ScheduleSpec, "platform" | "home" | "launchAgentsDir">,
): Promise<ScheduleResult> {
	if (s.platform === "win32") {
		const r = await exec("schtasks", ["/Delete", "/TN", TASK_NAME, "/F"], { timeoutMs: 30_000 });
		rmSync(join(s.home, "tick.vbs"), { force: true });
		// gorev zaten yoksa da "silindi" sayilir
		return {
			ok: r.code === 0 || /cannot find|bulunam|does not exist|not exist/i.test(r.stdout + r.stderr),
			detail: (r.stdout + r.stderr).trim().slice(0, 300),
		};
	}
	if (s.platform === "darwin") {
		const p = plistPath(s as ScheduleSpec);
		await exec("launchctl", ["unload", "-w", p], { timeoutMs: 15_000 });
		rmSync(p, { force: true });
		return { ok: true, detail: "launchd ajanı kaldırıldı" };
	}
	const cur = await exec("crontab", ["-l"], { timeoutMs: 15_000 });
	if (cur.code !== 0) return { ok: true, detail: "crontab yok" };
	const keep = cur.stdout.split("\n").filter((l) => l.trim() && !l.includes(CRON_MARK));
	const r = await exec("crontab", ["-"], { input: keep.length ? `${keep.join("\n")}\n` : "", timeoutMs: 15_000 });
	return { ok: r.code === 0, detail: (r.stdout + r.stderr).trim().slice(0, 300) };
}

export async function scheduleInstalled(
	exec: Exec,
	s: Pick<ScheduleSpec, "platform" | "home" | "launchAgentsDir">,
): Promise<boolean> {
	if (s.platform === "win32")
		return (await exec("schtasks", ["/Query", "/TN", TASK_NAME], { timeoutMs: 30_000 })).code === 0;
	if (s.platform === "darwin")
		return (await exec("launchctl", ["list", LAUNCHD_LABEL], { timeoutMs: 15_000 })).code === 0;
	const cur = await exec("crontab", ["-l"], { timeoutMs: 15_000 });
	return cur.code === 0 && cur.stdout.includes(CRON_MARK);
}

// ---------------------------------------------------------------- bildirim (PR acilinca)

/** Yonetici gerektirmez; modul yok: Windows PowerShell 5.1 yerlesik WinRT ToastNotification. */
export function notifyCommand(
	platform: NodeJS.Platform,
	title: string,
	body: string,
): { cmd: string; args: string[] } | undefined {
	const esc = (s: string) =>
		s
			.replace(/[\r\n]+/g, " ")
			.replace(/[<>&"'`$]/g, " ")
			.slice(0, 200);
	const t = esc(title);
	const b = esc(body);
	if (platform === "win32") {
		const ps =
			`$ErrorActionPreference='Stop';` +
			`[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];` +
			`[void][Windows.Data.Xml.Dom.XmlDocument,Windows.Data.Xml.Dom.XmlDocument,ContentType=WindowsRuntime];` +
			`$x=New-Object Windows.Data.Xml.Dom.XmlDocument;` +
			`$x.LoadXml('<toast><visual><binding template="ToastGeneric"><text>${t}</text><text>${b}</text></binding></visual></toast>');` +
			`$n=[Windows.UI.Notifications.ToastNotification]::new($x);` +
			`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show($n)`;
		return {
			cmd: "powershell.exe",
			args: ["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", ps],
		};
	}
	if (platform === "darwin")
		return { cmd: "osascript", args: ["-e", `display notification "${b}" with title "${t}"`] };
	return { cmd: "notify-send", args: [t, b] };
}

export async function notifyPr(exec: Exec, platform: NodeJS.Platform, repo: string, pr: string): Promise<boolean> {
	const c = notifyCommand(platform, "Sera bir değişiklik hazırladı", `${repo}: ${pr}`);
	if (!c) return false;
	try {
		return (await exec(c.cmd, c.args, { timeoutMs: 20_000 })).code === 0;
	} catch {
		return false;
	}
}
