import { loadEnvironmentFiles } from "../env.js";
import { createAgentsManageDatabaseClient } from "../db/manage/manage-client.js";
import { doltAddAndCommit, doltReset, doltStatus } from "./commit.js";
import { confirmMigration } from "../db/utils.js";
import { appendFileSync } from "node:fs";
import { execSync } from "node:child_process";

//#region src/dolt/migrate-dolt.ts
const commitMigrations = async () => {
	loadEnvironmentFiles();
	const connectionString = process.env.INKEEP_AGENTS_MANAGE_DATABASE_URL;
	await confirmMigration(connectionString);
	try {
		execSync("drizzle-kit migrate --config=drizzle.manage.config.ts", { stdio: "inherit" });
	} catch (error) {
		console.error("❌ Error running migrations:", error);
		process.exit(1);
	}
	const db = createAgentsManageDatabaseClient({ connectionString });
	let migrationsApplied = false;
	try {
		migrationsApplied = (await doltStatus(db)()).length > 0;
		if (migrationsApplied) await doltAddAndCommit(db)({ message: "Applied database migrations" });
		else console.log("ℹ️  No changes to commit - database is up to date\n");
	} catch (error) {
		console.error("❌ Error committing migrations, reverting:", error);
		try {
			await doltReset(db)({ hard: true });
			console.log("✓ Successfully reverted uncommitted changes.");
		} catch (resetError) {
			console.error("⚠️ Warning: Reset failed (connection may be dead):", resetError);
			console.error("Manual cleanup may be required: run DOLT_RESET('--hard') on the database.");
		}
		process.exit(1);
	}
	const ghOutput = process.env.GITHUB_OUTPUT;
	if (ghOutput) appendFileSync(ghOutput, `migrations_applied=${migrationsApplied}\n`);
};
commitMigrations();

//#endregion
export {  };