import { access, mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { getLogger } from "../util/logger.js";
/**
 * Generic helper that creates a CI workflow file for a given provider
 * if the repo's remote matches and the file doesn't already exist.
 */
export async function ensureWorkflowFile(gitService, config, superblocksBaseUrl) {
    const operationName = `ensure-${config.providerName}-workflow-file`;
    let remoteUrl;
    try {
        remoteUrl = (await gitService.raw(["remote", "get-url", "origin"])).trim();
    }
    catch (error) {
        getLogger().warn(`[git] ${operationName} failed to read origin URL`, {
            gitCategory: "setup",
            gitOperation: operationName,
            gitOutcome: "failed",
            gitErrorKind: "read_origin_url_failed",
            workDir: gitService.workDir,
            message: error instanceof Error ? error.message : String(error),
        });
        return { created: false };
    }
    if (!config.isProviderRemoteUrl(remoteUrl)) {
        return { created: false };
    }
    const workflowPath = join(gitService.workDir, config.workflowPath);
    try {
        await access(workflowPath);
        return { created: false };
    }
    catch (error) {
        if (error instanceof Error && "code" in error && error.code !== "ENOENT") {
            throw error;
        }
    }
    const resolvedUrl = superblocksBaseUrl || "";
    if (!resolvedUrl) {
        getLogger().warn(`[git] ${operationName}: no superblocksBaseUrl provided, workflow will use default prod domain`, {
            gitCategory: "setup",
            gitOperation: operationName,
            gitOutcome: "degraded",
        });
    }
    await mkdir(dirname(workflowPath), { recursive: true });
    await writeFile(workflowPath, config.buildWorkflowFromBaseUrl(resolvedUrl), "utf-8");
    getLogger().info(`[git] ${operationName}: created ${config.workflowPath}`);
    return { created: true };
}
//# sourceMappingURL=ensure-workflow-file.js.map