import { storageList } from './storage-client.js';
export const SKILLS_STORAGE_PREFIX = '.shortcut/skills/';
/** List all skill files for a given storage context. */
export async function listSkillFiles(accessToken, storageContext, ownerTeamId) {
    const options = ownerTeamId ? { teamId: ownerTeamId } : {};
    const entries = await storageList(accessToken, SKILLS_STORAGE_PREFIX, storageContext, options);
    return entries
        .filter((entry) => !entry.isDir)
        .map((entry) => ({
        entry,
        storagePath: `${SKILLS_STORAGE_PREFIX}${entry.path}`,
        storageContext,
        ...(ownerTeamId ? { ownerTeamId } : {})
    }));
}
export async function listAuthorizedTeamSkillFiles(accessToken, authorizedSkillTeamIds) {
    const files = [];
    const errors = [];
    for (const ownerTeamId of authorizedSkillTeamIds) {
        try {
            files.push(...(await listSkillFiles(accessToken, 'team', ownerTeamId)));
        }
        catch (error) {
            errors.push(formatTeamSkillsError(ownerTeamId, error));
        }
    }
    return { files, errors };
}
export function storageOwnerOptionsForRemoteSkillFile(file) {
    if (file.storageContext !== 'team')
        return {};
    if (!file.ownerTeamId) {
        throw new Error('Team skill file is missing ownerTeamId');
    }
    return { teamId: file.ownerTeamId };
}
export function groupRemoteFilesBySkill(files) {
    const grouped = new Map();
    for (const file of files) {
        const skillName = file.entry.path.split('/')[0];
        if (!skillName)
            continue;
        const existing = grouped.get(skillName);
        if (existing) {
            existing.push(file);
        }
        else {
            grouped.set(skillName, [file]);
        }
    }
    return grouped;
}
function uniqueOwnerTeamIds(files) {
    return Array.from(new Set(files.map((file) => file.ownerTeamId).filter((teamId) => !!teamId))).sort();
}
export function findDuplicateTeamSkills(teamBySkill) {
    const duplicates = [];
    for (const [skillName, files] of teamBySkill) {
        const ownerTeamIds = uniqueOwnerTeamIds(files);
        if (ownerTeamIds.length > 1) {
            duplicates.push({ skillName, ownerTeamIds });
        }
    }
    return duplicates.sort((a, b) => a.skillName.localeCompare(b.skillName));
}
export function formatDuplicateTeamSkillError(duplicate) {
    return `Team skill "${duplicate.skillName}" exists in multiple authorized teams (${duplicate.ownerTeamIds.join(', ')}); skipped because local skills cannot represent multiple team owners with the same folder name.`;
}
function formatTeamSkillsError(ownerTeamId, error) {
    const message = error instanceof Error ? error.message : String(error);
    return `Team skills (${ownerTeamId}): ${message}`;
}
//# sourceMappingURL=remote-skill-files.js.map