export const DEFAULT_AUTHORITY_PROVIDER = "mimo";
export const DEFAULT_FALLBACK_RUNTIME = "mimo-api";
export const DEFAULT_RUNTIME_FALLBACK_CHAIN = [
    DEFAULT_FALLBACK_RUNTIME,
    "codex-cli",
    "deepseek-api",
    "opencode-cli",
    "commandcode-cli",
];
const LEGACY_EXTERNAL_RUNTIME_MODES = new Set(["print", "wire"]);
export function resolveFallbackProvider(provider) {
    const candidates = Array.isArray(provider) ? provider : [provider];
    for (const candidate of candidates) {
        if (candidate && candidate !== "auto")
            return candidate;
    }
    return DEFAULT_AUTHORITY_PROVIDER;
}
export function resolveAuthorityProvider(availableProviders = [], preferredProvider) {
    if (preferredProvider && preferredProvider !== "auto" && availableProviders.includes(preferredProvider)) {
        return preferredProvider;
    }
    const defaultAuthority = availableProviders.find((provider) => provider === DEFAULT_AUTHORITY_PROVIDER);
    if (defaultAuthority)
        return defaultAuthority;
    const neutralProvider = availableProviders.find((provider) => provider !== "kimi" && provider !== "deepseek");
    if (neutralProvider)
        return neutralProvider;
    return DEFAULT_AUTHORITY_PROVIDER;
}
export function resolveFallbackRuntime(availableRuntimes = []) {
    return resolveRuntimeFallbackChain(availableRuntimes)[0] ?? DEFAULT_FALLBACK_RUNTIME;
}
export function resolveRuntimeFallbackChain(availableRuntimes = []) {
    const runtimes = availableRuntimes.length > 0
        ? [...availableRuntimes]
        : [...DEFAULT_RUNTIME_FALLBACK_CHAIN];
    return runtimes.sort((left, right) => runtimeFallbackRank(left) - runtimeFallbackRank(right));
}
function runtimeFallbackRank(runtimeId) {
    const defaultIndex = DEFAULT_RUNTIME_FALLBACK_CHAIN.indexOf(runtimeId);
    if (defaultIndex >= 0)
        return defaultIndex;
    if (LEGACY_EXTERNAL_RUNTIME_MODES.has(runtimeModeId(runtimeId)))
        return 10_000;
    return 5_000;
}
function runtimeModeId(runtimeId) {
    const [, ...modeParts] = runtimeId.toLowerCase().split("-");
    return modeParts.join("-");
}
export function withProviderMetadata(result, metadata) {
    return {
        ...result,
        metadata: {
            ...(result.metadata ?? {}),
            ...metadata,
        },
    };
}
