/**
 * github_ajan icin GERCEK bagimliliklar: gh girisini baslatma (tarayici akisi), Exec, varsayilan AkisDeps.
 * Mantik github-ajan-akis.ts'te; burasi I/O (testte kullanilmaz, sahte bagimlilik verilir).
 */
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { defaultHome } from "./github-agent.ts";
import { makeRunner } from "./github-agent-engine.ts";
import type { Exec } from "./github-agent-schedule.ts";
import type { AkisDeps } from "./github-ajan-akis.ts";

export const realExec: Exec = (cmd, args, opts = {}) =>
	new Promise((resolve) => {
		let out = "";
		let err = "";
		let done = false;
		const fin = (code: number) => {
			if (done) return;
			done = true;
			clearTimeout(t);
			resolve({ code, stdout: out, stderr: err });
		};
		const child = spawn(cmd, args, { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
		const t = setTimeout(() => {
			err += "\n[zaman asimi]";
			try {
				child.kill();
			} catch {
				// kapanmis
			}
			fin(124);
		}, opts.timeoutMs ?? 30_000);
		child.stdout.setEncoding("utf8").on("data", (d: string) => {
			out += d;
		});
		child.stderr.setEncoding("utf8").on("data", (d: string) => {
			err += d;
		});
		child.on("error", (e) => {
			err += String(e);
			fin(127);
		});
		child.on("close", (c) => fin(c ?? 1));
		child.stdin.on("error", () => {});
		child.stdin.end(opts.input ?? "");
	});

/** `gh auth login --web`: tek kullanimlik kodu yakalar, surec tarayici onayini beklerken arka planda kalir. */
export function startGhLogin(): Promise<{ started: boolean; code?: string }> {
	return new Promise((resolve) => {
		let buf = "";
		let settled = false;
		const fin = (v: { started: boolean; code?: string }) => {
			if (settled) return;
			settled = true;
			clearTimeout(t);
			resolve(v);
		};
		let child: ReturnType<typeof spawn>;
		try {
			child = spawn("gh", ["auth", "login", "--web", "-h", "github.com", "-p", "https", "-s", "repo,read:org"], {
				windowsHide: true,
				detached: true,
				stdio: ["pipe", "pipe", "pipe"],
			});
		} catch {
			return resolve({ started: false });
		}
		const onData = (d: Buffer) => {
			buf += d.toString("utf8");
			const m = buf.match(/\b([A-Z0-9]{4}-[A-Z0-9]{4})\b/);
			if (m) {
				child.unref();
				fin({ started: true, code: m[1] });
			}
		};
		child.stdout?.on("data", onData);
		child.stderr?.on("data", onData);
		child.on("error", () => fin({ started: false }));
		child.stdin?.on("error", () => {});
		child.stdin?.write("\n"); // "Enter'a bas, tarayici acilsin"
		const t = setTimeout(() => {
			child.unref();
			fin({ started: true });
		}, 15_000);
	});
}

export function realAkisDeps(cwd: string, engine: { entry: string; args: string[] }): AkisDeps {
	return {
		run: makeRunner(),
		exec: realExec,
		home: defaultHome(),
		now: () => Date.now(),
		platform: process.platform,
		cwd,
		startLogin: startGhLogin,
		node: process.execPath,
		tickScript: fileURLToPath(new URL("./github-tick.ts", import.meta.url)),
		engine,
	};
}
