import { RegistryError } from './types.js';
function parseRepo(url) {
    const u = url.trim().replace(/^git@github\.com:/, 'https://github.com/');
    const m = u.match(/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/(?:tree|blob)\/([^/]+)\/?(.*))?$/);
    if (!m)
        throw new RegistryError('Not a GitHub URL', 400);
    return { owner: m[1], repo: m[2], ref: m[3] ?? 'HEAD', path: m[4] ?? null };
}
async function fetchJson(url) {
    const res = await fetch(url, { headers: { accept: 'application/json' } });
    if (!res.ok)
        throw new RegistryError(`GitHub fetch failed: ${url} ${res.status}`);
    return res.json();
}
async function fetchText(url) {
    const res = await fetch(url);
    if (!res.ok)
        throw new RegistryError(`GitHub fetch failed: ${url} ${res.status}`);
    return res.text();
}
export const githubUrlAdapter = {
    descriptor: {
        id: 'github-url',
        label: 'From GitHub URL',
        kinds: ['skill', 'mcp'],
        requiresAuth: false,
        enabled: true
    },
    async search(query) {
        if (!query.trim())
            return [];
        const ref = parseRepo(query);
        const candidates = [];
        const skillPath = ref.path && ref.path.endsWith('SKILL.md') ? ref.path : null;
        if (skillPath) {
            candidates.push({
                id: query,
                source: 'github-url',
                kind: 'skill',
                name: skillPath.split('/').slice(-2, -1)[0] || ref.repo,
                title: ref.repo,
                description: null,
                version: ref.ref === 'HEAD' ? null : ref.ref,
                repository: `https://github.com/${ref.owner}/${ref.repo}`,
                homepage: null,
                installManifest: { ...ref, kind: 'skill', skillPath }
            });
            return candidates;
        }
        try {
            const marketplaceUrl = `https://raw.githubusercontent.com/${ref.owner}/${ref.repo}/${ref.ref}/.claude-plugin/marketplace.json`;
            const text = await fetchText(marketplaceUrl);
            const manifest = JSON.parse(text);
            for (const plugin of manifest.plugins ?? []) {
                candidates.push({
                    id: `${query}#${plugin.name}`,
                    source: 'github-url',
                    kind: 'skill',
                    name: plugin.name,
                    title: ref.repo,
                    description: plugin.description ?? null,
                    version: ref.ref === 'HEAD' ? null : ref.ref,
                    repository: `https://github.com/${ref.owner}/${ref.repo}`,
                    homepage: null,
                    installManifest: { ...ref, kind: 'marketplace', plugin }
                });
            }
        }
        catch {
            // fall through
        }
        if (candidates.length === 0) {
            try {
                const skillUrl = `https://raw.githubusercontent.com/${ref.owner}/${ref.repo}/${ref.ref}/SKILL.md`;
                await fetchText(skillUrl);
                candidates.push({
                    id: query,
                    source: 'github-url',
                    kind: 'skill',
                    name: ref.repo,
                    title: ref.repo,
                    description: null,
                    version: ref.ref === 'HEAD' ? null : ref.ref,
                    repository: `https://github.com/${ref.owner}/${ref.repo}`,
                    homepage: null,
                    installManifest: { ...ref, kind: 'skill', skillPath: 'SKILL.md' }
                });
            }
            catch {
                // no skill at root
            }
        }
        return candidates;
    },
    async resolveInstall(entry) {
        const raw = entry.installManifest;
        if (raw.kind === 'skill' && raw.skillPath) {
            const text = await fetchText(`https://raw.githubusercontent.com/${raw.owner}/${raw.repo}/${raw.ref}/${raw.skillPath}`);
            return {
                name: entry.name,
                skillMarkdown: text,
                source: {
                    registry: 'github-url',
                    ref: `${raw.owner}/${raw.repo}@${raw.ref}`,
                    version: raw.ref === 'HEAD' ? null : raw.ref,
                    url: `https://github.com/${raw.owner}/${raw.repo}`
                }
            };
        }
        if (raw.kind === 'marketplace' && raw.plugin) {
            const skillPath = `${raw.plugin.name}/SKILL.md`;
            const text = await fetchText(`https://raw.githubusercontent.com/${raw.owner}/${raw.repo}/${raw.ref}/${skillPath}`);
            return {
                name: raw.plugin.name,
                skillMarkdown: text,
                source: {
                    registry: 'github-url',
                    ref: `${raw.owner}/${raw.repo}@${raw.ref}`,
                    version: raw.ref === 'HEAD' ? null : raw.ref,
                    url: `https://github.com/${raw.owner}/${raw.repo}`
                }
            };
        }
        throw new RegistryError('Unsupported GitHub install entry', 422);
    }
};
void fetchJson; // exported import retained for future use
//# sourceMappingURL=github-url.js.map