import { Type } from "@sinclair/typebox";
import { FirRouteInput, FirRouteOptions } from "../util/routewrap.js";
import fs from "fs";
import path from "path";
import git from "isomorphic-git";
import http from "isomorphic-git/http/node";
import {fileURLToPath} from 'url';
import { pico8 } from "../util/pico8.js";
const __dirname = fileURLToPath(new URL('.', import.meta.url));

const method = "POST";
const url = "/api/release";

// const payloadT = Type.Object({
// 	png: Type.String(),
// });

const payloadT = Type.Any();

const repoPath = path.resolve(__dirname, "..", "..", "..", "repo");

// const {stdout, } = await execa(picoBinPath, ["/home/dylan/.lexaloffle/pico-8/carts/candles/candles.p8", "-export", path.join(__dirname, "result.js")]);
// const {stdout, } = await execa("ls", ["-la", picoDirPath]);
// console.log(stdout);

// const {stdout: stdout2, } = await execa(picoBinPath, ["-x"]);
// console.log(stdout2);

const handler = async ({payload}: FirRouteInput<typeof payloadT>) => {
	const {manifest, token} = payload;
	if (!fs.existsSync(repoPath)) {
		fs.mkdirSync(repoPath, {recursive: true})
	}
	console.log(manifest);
	console.log("cloning...");
	await git.clone({
		fs,
		http,
		// headers: {
		// 	"Authorization": `Bearer ${token}`,
		// },
		onAuth() {
			return {
				username: 'x-access-token',
				password: token,
			}
		},
		dir: repoPath,
		url: manifest.repo,
	});
	console.log("cloned");
	console.log("read local manifest");
	console.log("manifest exists: ", fs.existsSync(path.join(repoPath, "picobook.json")));
	console.log("main exists: ", fs.existsSync(path.join(repoPath, manifest.main)));
	// const {stdout} = await execa("ls", ["-la", picoDirPath], {shell: true});
	// console.log(stdout);
	const exported=await pico8.export(path.join(repoPath, manifest.main), path.join(repoPath, "result.js"));
	console.log((exported as any).stdout);
	// await execa(picoBinPath, [path.join(repoPath, manifest.main), "-export", path.join(repoPath, "result.js")]);
	// await execa(picoBinPath, [path.join(repoPath, manifest.main), "-export", path.join(repoPath, "result.png")]);
	const js = await fs.promises.readFile(path.join(repoPath, "result.js"), "utf8");
	// const png = Buffer.from(await fs.promises.readFile(path.join(repoPath, "result.png"))).toString("base64");
	fs.promises.rm(repoPath, {recursive: true, force: true});
	console.log({
		manifest,
		js,
		// png,
	});
	return true;
};

export default {
	method,
	url,
	payloadT,
	handler,
} as const satisfies FirRouteOptions<typeof payloadT>;