// deno-lint-ignore-file no-explicit-any
import * as dntShim from "../../../_dnt.shims.js";
import { isSuperset, parseFromFile, removeType, } from "../../types.js";
import { requireLogin } from "../../core/auth.js";
import { resolveWorkspace, validatePath } from "../../core/context.js";
import { colors, Command, log, SEP, Table } from "../../../deps.js";
import * as wmill from "../../../gen/services.gen.js";
import { readInlinePathSync } from "../../utils/utils.js";
import { isBranchSpecificFile } from "../../core/specific_items.js";
import { getCurrentGitBranch } from "../../utils/git.js";
export async function pushResource(workspace, remotePath, resource, localResource, originalLocalPath) {
    remotePath = removeType(remotePath, "resource");
    try {
        resource = await wmill.getResource({
            workspace: workspace,
            path: remotePath.replaceAll(SEP, "/"),
        });
    }
    catch {
        // flow doesn't exist
    }
    // Helper function to resolve inline content
    const resolveInlineContent = async () => {
        if (localResource.value["content"]?.startsWith("!inline ")) {
            const basePath = localResource.value["content"].split(" ")[1];
            // If we're processing a branch-specific metadata file, read from branch-specific resource file
            let pathToRead = basePath;
            if (originalLocalPath && isBranchSpecificFile(originalLocalPath)) {
                const currentBranch = getCurrentGitBranch();
                if (currentBranch) {
                    // Directly construct branch-specific resource file path
                    const resourcePathSegments = basePath.split(".");
                    if (resourcePathSegments.length >= 4 && resourcePathSegments[resourcePathSegments.length - 3] === "resource" && resourcePathSegments[resourcePathSegments.length - 2] === "file") {
                        const fileBaseParts = resourcePathSegments.slice(0, -3);
                        const fileExt = resourcePathSegments.slice(-3);
                        pathToRead = [...fileBaseParts, currentBranch, ...fileExt].join(".");
                    }
                }
            }
            localResource.value["content"] = readInlinePathSync(pathToRead);
        }
    };
    if (resource) {
        if (isSuperset(localResource, resource)) {
            return;
        }
        // Only resolve inline content if we're actually updating
        await resolveInlineContent();
        await wmill.updateResource({
            workspace: workspace,
            path: remotePath.replaceAll(SEP, "/"),
            requestBody: { ...localResource },
        });
    }
    else {
        // New resource - resolve inline content
        await resolveInlineContent();
        if (localResource.is_oauth) {
            log.info(colors.yellow("! is_oauth has been removed in newer versions. Ignoring."));
        }
        log.info(colors.yellow.bold("Creating new resource..."));
        await wmill.createResource({
            workspace: workspace,
            requestBody: {
                path: remotePath.replaceAll(SEP, "/"),
                ...localResource,
            },
        });
    }
}
async function push(opts, filePath, remotePath) {
    const workspace = await resolveWorkspace(opts);
    await requireLogin(opts);
    if (!validatePath(remotePath)) {
        return;
    }
    const fstat = await dntShim.Deno.stat(filePath);
    if (!fstat.isFile) {
        throw new Error("file path must refer to a file.");
    }
    log.info(colors.bold.yellow("Pushing resource..."));
    await pushResource(workspace.workspaceId, remotePath, undefined, parseFromFile(filePath), filePath // Pass the local file path for branch-specific inline content resolution
    );
    log.info(colors.bold.underline.green(`Resource ${remotePath} pushed`));
}
async function list(opts) {
    const workspace = await resolveWorkspace(opts);
    await requireLogin(opts);
    let page = 0;
    const perPage = 10;
    const total = [];
    while (true) {
        const res = await wmill.listResource({
            workspace: workspace.workspaceId,
            page,
            perPage,
        });
        total.push(...res);
        page += 1;
        if (res.length < perPage) {
            break;
        }
    }
    new Table()
        .header(["Path", "Resource Type"])
        .padding(2)
        .border(true)
        .body(total.map((x) => [x.path, x.resource_type]))
        .render();
}
const command = new Command()
    .description("resource related commands")
    .action(list)
    .command("push", "push a local resource spec. This overrides any remote versions.")
    .arguments("<file_path:string> <remote_path:string>")
    .action(push);
export default command;
