import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import axios from "axios";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Get version and changelog
const pkg = JSON.parse(
	readFileSync(join(__dirname, "../package.json"), "utf8"),
);
const version = `v${pkg.version}`;
const changelog = readFileSync(join(__dirname, "../CHANGELOG.md"), "utf8");

// Extract latest release notes (between first two headings)
const latestNotes =
	changelog.split("\n## ")[1]?.split("\n").slice(1).join("\n") ||
	"No changes documented";

try {
	const response = await axios.post(
		"https://git.tuffraid.net/api/v1/repos/cowch/lst_v3/releases",
		{
			tag_name: version,
			name: version,
			body: latestNotes,
			draft: false,
			prerelease: false,
		},
		{
			headers: {
				Authorization: `token ${process.env.GITEA_TOKEN}`,
				"Content-Type": "application/json",
			},
		},
	);

	console.info(`✅ Release ${version} created!`);
	console.info(`🔗 ${response.data.html_url}`);
} catch (error) {
	console.error(`❌ Error: ${error.response?.data?.message || error.message}`);
	process.exit(1);
}
