import { Type } from "@sinclair/typebox";
import { FirRouteInput, FirRouteOptions } from "../util/routewrap.js";
import {execa} from 'execa';
import fs from "fs";
import path from "path";
import git from "isomorphic-git";
import http from "isomorphic-git/http/node";
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
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 picoBinPath = path.resolve(__dirname, "..", "..", "..", "pico8", "pico8");

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

// console.log(stdout);

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("pico exists: ", fs.existsSync(picoBinPath));
	console.log("manifest exists: ", fs.existsSync(path.join(repoPath, "picobook.json")));
	console.log("main exists: ", fs.existsSync(path.join(repoPath, manifest.main)));
	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>;