"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listTemplates = listTemplates;
exports.getTemplate = getTemplate;
exports.listVersionsFor = listVersionsFor;
exports.pickDefault = pickDefault;
exports.fetchRawFile = fetchRawFile;
exports.parseFrameworkArg = parseFrameworkArg;
const TEMPLATE_ORG = 'flui-cloud';
const DEFAULT_BRANCH = 'main';
async function listTemplates(api) {
    return api.get('/templates');
}
async function getTemplate(api, framework, version) {
    const path = version
        ? `/templates/${framework}?version=${encodeURIComponent(version)}`
        : `/templates/${framework}`;
    return api.get(path);
}
async function listVersionsFor(api, framework) {
    const all = await listTemplates(api);
    return all
        .filter((t) => t.framework === framework)
        .sort((a, b) => Number(b.version) - Number(a.version));
}
function pickDefault(entries) {
    return (entries.find((t) => t.isDefault && !t.isDeprecated) ??
        entries.find((t) => !t.isDeprecated) ??
        entries[0]);
}
async function fetchRawFile(repo, filename, branch = DEFAULT_BRANCH) {
    const url = `https://raw.githubusercontent.com/${TEMPLATE_ORG}/${repo}/${branch}/${filename}`;
    const res = await fetch(url);
    if (!res.ok) {
        throw new Error(`Failed to fetch ${filename} from ${TEMPLATE_ORG}/${repo}@${branch}: HTTP ${res.status}`);
    }
    return await res.text();
}
function parseFrameworkArg(input) {
    const at = input.indexOf('@');
    if (at === -1) {
        return { framework: input };
    }
    return {
        framework: input.slice(0, at),
        version: input.slice(at + 1),
    };
}
