import path from "path"
import fs from "fs"

import { zodToTs, createTypeAlias, printNode } from "zod-to-ts"
import { $ } from "execa"

import schemas from "../schemas"

const { typeDefinitions } = schemas

async function main() {
	const types: string[] = [
		"// This file is automatically generated by running `pnpm --filter roo-cline generate-types`\n// Do not edit it directly.",
	]

	for (const { schema, identifier } of typeDefinitions) {
		types.push(printNode(createTypeAlias(zodToTs(schema, identifier).node, identifier)))
		types.push(`export type { ${identifier} }`)
	}

	fs.writeFileSync("exports/types.ts", types.join("\n\n"))

	await $`npx tsup exports/interface.ts --dts -d out`
	fs.copyFileSync("out/interface.d.ts", "exports/roo-code.d.ts")

	await $`npx prettier --write exports/types.ts exports/roo-code.d.ts`

	if (fs.existsSync(path.join("..", "..", "Roo-Code-Types", "src"))) {
		fs.copyFileSync("out/interface.js", path.join("..", "..", "Roo-Code-Types", "src", "index.js"))
		fs.copyFileSync("out/interface.d.ts", path.join("..", "..", "Roo-Code-Types", "src", "index.d.ts"))
	}
}

main()
