import { execSync } from "child_process";
import fs from "fs";
import path from "path";

const appJsonPath = path.resolve("../app.json");

// detect flags
const args = process.argv.slice(2);
const shouldBumpMin = args.includes("--bump");

try {
	// 📖 read file
	const raw = fs.readFileSync(appJsonPath, "utf-8");
	const json = JSON.parse(raw);

	const expo = json.expo ?? json; // supports both formats

	if (!expo.android) {
		throw new Error("No android config found in app.json");
	}

	// 🔢 current values
	const currentVersionCode = expo.android.versionCode ?? 1;
	const currentMin = expo.android.minSupportedVersionCode ?? 1;

	// 🚀 increment version
	const newVersionCode = currentVersionCode + 1;

	expo.android.versionCode = newVersionCode;

	if (shouldBumpMin) {
		expo.android.minSupportedVersionCode = newVersionCode;
	} else {
		// keep existing min if not bumping
		expo.android.minSupportedVersionCode = currentMin;
	}

	// 💾 write back
	fs.writeFileSync(appJsonPath, JSON.stringify(json, null, 2));

	console.log("✅ app.json updated:");
	console.log("   versionCode:", newVersionCode);
	console.log(
		"   minSupportedVersionCode:",
		expo.android.minSupportedVersionCode,
	);

	// 🏗 run build
	console.log("\n🚧 Running build:apk...\n");
	execSync("npm run build:apk", { stdio: "inherit" });

	console.log("\n🎉 Build complete!");
} catch (err) {
	console.error("❌ Build script failed:");
	console.error(err);
	process.exit(1);
}
