"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.githubProjectRefCapabilities = void 0;
exports.normalizeGitHubProjectRef = normalizeGitHubProjectRef;
exports.parseGitHubProjectRef = parseGitHubProjectRef;
exports.buildGitHubRemoteUrl = buildGitHubRemoteUrl;
exports.detectGitHubProjectRefFromRemoteUrl = detectGitHubProjectRefFromRemoteUrl;
exports.toGitHubStorageSegments = toGitHubStorageSegments;
const catalog_1 = require("../../i18n/catalog");
const project_ref_support_1 = require("../project-ref-support");
function normalizeGitHubProjectRef(projectRef, locale = catalog_1.DEFAULT_APP_LOCALE) {
    const { owner, repo } = parseGitHubProjectRef(projectRef.trim(), locale);
    return `${owner}/${repo}`;
}
function parseGitHubProjectRef(projectRef, locale = catalog_1.DEFAULT_APP_LOCALE) {
    const parsed = parseGitHubProjectRefInput(projectRef.trim());
    if (parsed === null) {
        throw new Error((0, catalog_1.translate)(locale, "github.projectRef.invalid", { projectRef }));
    }
    return parsed;
}
function buildGitHubRemoteUrl(projectRef, locale = catalog_1.DEFAULT_APP_LOCALE) {
    const { owner, repo } = parseGitHubProjectRef(projectRef, locale);
    return `https://github.com/${owner}/${repo}.git`;
}
function detectGitHubProjectRefFromRemoteUrl(remoteUrl) {
    return exports.githubProjectRefCapabilities.detectProjectRefFromRemoteUrl(remoteUrl);
}
function toGitHubStorageSegments(projectRef, locale = catalog_1.DEFAULT_APP_LOCALE) {
    const { owner, repo } = parseGitHubProjectRef(projectRef, locale);
    return [owner, repo];
}
exports.githubProjectRefCapabilities = (0, project_ref_support_1.createProjectRefCapabilities)({
    normalizeProjectRef: normalizeGitHubProjectRef,
    parseProjectRef: parseGitHubProjectRef,
    toStorageSegments: toGitHubStorageSegments,
});
function parseGitHubProjectRefInput(projectRef) {
    const shorthandSegments = (0, project_ref_support_1.parseShorthandProjectRefSegments)(projectRef, {
        prefix: "github:",
        minSegments: 2,
        maxSegments: 2,
    });
    if (shorthandSegments !== null) {
        const [owner = "", repo = ""] = shorthandSegments;
        return { owner, repo };
    }
    const remoteProjectRef = (0, project_ref_support_1.parseProviderRemoteProjectRef)(projectRef, {
        host: "github.com",
        namespaceSegments: { kind: "exact", count: 1 },
    });
    if (remoteProjectRef === null) {
        return null;
    }
    const [owner = ""] = remoteProjectRef.namespaceSegments;
    return owner && remoteProjectRef.repo
        ? { owner, repo: remoteProjectRef.repo }
        : null;
}
