"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseGithubRepo = parseGithubRepo;
exports.normalizeGithubDirectoryPath = normalizeGithubDirectoryPath;
exports.fetchGithubSkillMarkdownPaths = fetchGithubSkillMarkdownPaths;
exports.readGithubSkillMetadata = readGithubSkillMetadata;
exports.resolveImportedSkillId = resolveImportedSkillId;
const skill_metadata_1 = require("../core/skill-metadata");
const github_http_1 = require("../catalog/github-http");
const skill_inventory_1 = require("../workflows/skill-inventory");
function parseGithubRepo(value) {
    const trimmed = value.trim();
    const match = /^([^/\s]+)\/([^/\s]+)$/u.exec(trimmed);
    if (match === null) {
        throw new Error(`Invalid GitHub repository: ${value}`);
    }
    return {
        owner: match[1] ?? "",
        repo: match[2] ?? "",
    };
}
function normalizeGithubDirectoryPath(value, label) {
    const trimmed = value.trim().replace(/^\/+|\/+$/gu, "");
    if (trimmed.length === 0 ||
        trimmed
            .split("/")
            .some((segment) => segment === "" || segment === "." || segment === "..")) {
        throw new Error(`Invalid GitHub ${label}: ${value}`);
    }
    return trimmed;
}
async function fetchGithubSkillMarkdownPaths(input) {
    const response = await fetch(`https://api.github.com/repos/${encodeURIComponent(input.repo.owner)}/${encodeURIComponent(input.repo.repo)}/git/trees/${encodeURIComponent(input.ref)}?recursive=1`, { headers: (0, github_http_1.buildGithubHeaders)(input.env ?? process.env) });
    if (!response.ok) {
        throw new Error(`GitHub skills tree request failed: HTTP ${response.status}`);
    }
    const parsed = (await response.json());
    if (parsed.truncated === true) {
        throw new Error("GitHub skills tree response was truncated. Narrow --path or import from a smaller repository directory.");
    }
    return (parsed.tree ?? [])
        .filter((entry) => entry.type === "blob")
        .map((entry) => entry.path)
        .filter((entryPath) => entryPath !== undefined)
        .filter((entryPath) => isSkillMarkdownPath(entryPath, input.rootPath))
        .sort();
}
async function readGithubSkillMetadata(input) {
    const response = await fetch(`https://raw.githubusercontent.com/${encodeURIComponent(input.repo.owner)}/${encodeURIComponent(input.repo.repo)}/${encodeURIComponent(input.ref)}/${input.skillPath.split("/").map(encodeURIComponent).join("/")}`, { headers: (0, github_http_1.buildGithubHeaders)(input.env ?? process.env) });
    if (!response.ok) {
        return null;
    }
    return (0, skill_metadata_1.readSkillMetadataFromMarkdown)(await response.text());
}
function resolveImportedSkillId(metadataName, fallbackId) {
    if (metadataName !== null && (0, skill_inventory_1.isValidBareSkillId)(metadataName)) {
        return metadataName;
    }
    return (0, skill_inventory_1.isValidBareSkillId)(fallbackId) ? fallbackId : null;
}
function isSkillMarkdownPath(entryPath, rootPath) {
    return (entryPath === `${rootPath}/SKILL.md` ||
        (entryPath.startsWith(`${rootPath}/`) && entryPath.endsWith("/SKILL.md")));
}
