import { splitModelRegistryKey, withRegistryKey } from './registry-helpers.js';
export function getProviderLookupCandidates(providerName, aliases) {
    const candidates = new Set([providerName]);
    const directAlias = aliases[providerName];
    if (directAlias)
        candidates.add(directAlias);
    for (const [catalogName, registeredName] of Object.entries(aliases)) {
        if (registeredName === providerName)
            candidates.add(catalogName);
        if (directAlias && registeredName === directAlias)
            candidates.add(catalogName);
    }
    return [...candidates];
}
export function findModelDefinition(modelId, registry) {
    if (modelId.includes(':')) {
        return registry.find((model) => model.registryKey === modelId) ?? registry.find((model) => model.id === modelId);
    }
    return registry.find((model) => model.id === modelId);
}
export function findModelDefinitionForProvider(modelId, providerName, registry, aliases) {
    const providerCandidates = new Set(getProviderLookupCandidates(providerName, aliases));
    const resolvedModelId = modelId.includes(':') ? splitModelRegistryKey(modelId).resolvedModelId : modelId;
    const registryMatch = modelId.includes(':')
        ? findModelDefinition(modelId, registry)
        : undefined;
    if (registryMatch && providerCandidates.has(registryMatch.provider)) {
        return registryMatch;
    }
    return registry.find((model) => model.id === resolvedModelId && providerCandidates.has(model.provider));
}
export function buildModelRegistry(input) {
    const catalogFiltered = input.catalogModels.filter((builtin) => !input.customModels.some((model) => model.id === builtin.id) &&
        !input.runtimeModels.some((model) => model.id === builtin.id) &&
        !input.suppressedCatalogIds.has(builtin.id) &&
        !builtin.id.startsWith('hf:'));
    const discoveredFiltered = input.discoveredModels.filter((discovered) => !input.catalogModels.some((model) => model.id === discovered.id) &&
        !input.customModels.some((model) => model.id === discovered.id) &&
        !input.runtimeModels.some((model) => model.id === discovered.id));
    return [
        ...input.customModels.map(withRegistryKey),
        ...input.runtimeModels.map(withRegistryKey),
        ...input.syntheticModels.map(withRegistryKey),
        ...catalogFiltered.map(withRegistryKey),
        ...discoveredFiltered.map(withRegistryKey),
    ];
}
