import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { format } from "prettier";
import { StandardUpgrader } from "./lib.js";
export class FailedToParsePackageJson extends Error {
    constructor() {
        super("Invalid package.json: Failed to parse the package.json file.");
        Object.setPrototypeOf(this, FailedToParsePackageJson.prototype);
    }
}
export class PackageJsonUpgrader extends StandardUpgrader {
    async isApplicable() {
        try {
            const rawPackage = await readFile(join(this.normalizedDir, "package.json"), "utf-8");
            JSON.parse(rawPackage);
            return { ok: true };
        }
        catch {
            return { ok: false, error: new FailedToParsePackageJson() };
        }
    }
    async upgrade() {
        const packageJsonFile = join(this.normalizedDir, "package.json");
        const rawPackage = await readFile(packageJsonFile, "utf-8");
        const packageJson = JSON.parse(rawPackage);
        packageJson.scripts.dev = "zuplo dev";
        if (packageJson.scripts.build &&
            (packageJson.scripts.build === "zup build" ||
                packageJson.scripts.build === "zuplo build"))
            delete packageJson.scripts.build;
        if (packageJson.scripts.test && packageJson.scripts.test === "zup test") {
            packageJson.scripts.test = "zuplo test";
        }
        else if (!packageJson.scripts.test) {
            packageJson.scripts.test = "zuplo test";
        }
        if (packageJson.scripts.postinstall &&
            packageJson.scripts.postinstall === "husky install") {
            delete packageJson.scripts.postinstall;
        }
        packageJson.dependencies["zuplo"] = "latest";
        if (packageJson.dependencies["@zuplo/runtime"]) {
            delete packageJson.dependencies["@zuplo/runtime"];
        }
        if (packageJson.dependencies["@zuplo/core"]) {
            delete packageJson.dependencies["@zuplo/core"];
        }
        if (packageJson.devDependencies) {
            if (packageJson.devDependencies["@zuplo/test"])
                delete packageJson.devDependencies["@zuplo/test"];
            if (packageJson.devDependencies["husky"])
                delete packageJson.devDependencies["husky"];
            if (packageJson.devDependencies["chai"])
                delete packageJson.devDependencies["chai"];
            if (packageJson.devDependencies["@types/chai"])
                delete packageJson.devDependencies["@types/chai"];
        }
        const formatted = await format(JSON.stringify(packageJson), {
            parser: "json-stringify",
            quoteProps: "as-needed",
        });
        await writeFile(packageJsonFile, formatted);
    }
}
//# sourceMappingURL=package-json-upgrader.js.map