import chalk from "chalk";
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
import { findPreferredAvailableModel } from "./model-resolver-defaults.js";
import { buildFallbackModel } from "./model-resolver-patterns.js";
import { resolveCliModel } from "./model-resolver-cli.js";
async function buildConfiguredProviderFallbackModel(provider, modelId, modelRegistry) {
    return buildFallbackModel(provider, modelId, await modelRegistry.getAvailable());
}
/**
 * Resolve a model reference persisted in a session. Exact unauthenticated
 * models are authoritative failures; only an absent id may be reconstructed
 * from an authenticated model for the same dynamic/custom provider.
 */
export async function resolveRestoredModelReference(provider, modelId, modelRegistry) {
    const found = modelRegistry.find(provider, modelId);
    if (found)
        return modelRegistry.hasConfiguredAuth(found) ? found : undefined;
    if (!modelRegistry.canRestoreUnknownModel(provider))
        return undefined;
    return buildConfiguredProviderFallbackModel(provider, modelId, modelRegistry);
}
/**
 * Find the initial model to use based on priority:
 * 1. CLI args (provider + model)
 * 2. First model from scoped models (if not continuing/resuming)
 * 3. Restored from session (if continuing/resuming)
 * 4. Saved default from settings
 * 5. First available model with valid API key
 */
export async function findInitialModel(options) {
    const { cliProvider, cliModel, scopedModels, isContinuing, defaultProvider, defaultModelId, defaultThinkingLevel, modelRegistry, } = options;
    let model;
    let thinkingLevel = DEFAULT_THINKING_LEVEL;
    if (cliProvider && cliModel) {
        const resolved = resolveCliModel({
            cliProvider,
            cliModel,
            modelRegistry,
        });
        if (resolved.error) {
            console.error(chalk.red(resolved.error));
            process.exit(1);
        }
        if (resolved.model) {
            return {
                model: resolved.model,
                thinkingLevel: DEFAULT_THINKING_LEVEL,
                fallbackMessage: undefined,
            };
        }
    }
    if (scopedModels.length > 0 && !isContinuing) {
        return {
            model: scopedModels[0].model,
            thinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,
            fallbackMessage: undefined,
        };
    }
    if (defaultProvider && defaultModelId) {
        const found = modelRegistry.find(defaultProvider, defaultModelId);
        if (found && modelRegistry.hasConfiguredAuth(found)) {
            model = found;
            if (defaultThinkingLevel) {
                thinkingLevel = defaultThinkingLevel;
            }
            return { model, thinkingLevel, fallbackMessage: undefined };
        }
    }
    const availableModels = await modelRegistry.getAvailable();
    if (availableModels.length > 0) {
        return {
            model: findPreferredAvailableModel(availableModels),
            thinkingLevel: DEFAULT_THINKING_LEVEL,
            fallbackMessage: undefined,
        };
    }
    return {
        model: undefined,
        thinkingLevel: DEFAULT_THINKING_LEVEL,
        fallbackMessage: undefined,
    };
}
/**
 * Restore model from session, with fallback to available models
 */
export async function restoreModelFromSession(savedProvider, savedModelId, currentModel, shouldPrintMessages, modelRegistry) {
    const exactRestoredModel = modelRegistry.find(savedProvider, savedModelId);
    const restoredModel = await resolveRestoredModelReference(savedProvider, savedModelId, modelRegistry);
    if (restoredModel) {
        if (shouldPrintMessages) {
            console.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`));
        }
        return { model: restoredModel, fallbackMessage: undefined };
    }
    const reason = !exactRestoredModel ? "model no longer exists" : "no auth configured";
    if (shouldPrintMessages) {
        console.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));
    }
    if (currentModel) {
        if (shouldPrintMessages) {
            console.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));
        }
        return {
            model: currentModel,
            fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,
        };
    }
    const availableModels = await modelRegistry.getAvailable();
    const fallbackModel = findPreferredAvailableModel(availableModels);
    if (fallbackModel) {
        if (shouldPrintMessages) {
            console.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));
        }
        return {
            model: fallbackModel,
            fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,
        };
    }
    return { model: undefined, fallbackMessage: undefined };
}
//# sourceMappingURL=model-resolver-initial.js.map