import { logger } from '../utils/logger.js';
import { loadSystemPrompt as _loadSystemPrompt } from '../utils/prompt-loader.js';
import { isAbsolute, resolve } from 'node:path';
import { summarizeError } from '../utils/error-display.js';
function requireOwnedPromptRoot(path, name) {
    const trimmed = path?.trim();
    if (!trimmed) {
        throw new Error(`loadRuntimeSystemPrompt requires ConfigManager with explicit ${name}.`);
    }
    return trimmed;
}
export function loadRuntimeSystemPrompt(configManager) {
    const workingDirectory = requireOwnedPromptRoot(configManager.getWorkingDirectory(), 'workingDirectory');
    const homeDirectory = requireOwnedPromptRoot(configManager.getHomeDirectory(), 'homeDirectory');
    return _loadSystemPrompt({
        workingDirectory,
        homeDirectory,
        getConfigPath: () => {
            const configuredPath = configManager.get('provider.systemPromptFile');
            if (typeof configuredPath !== 'string' || !configuredPath.trim())
                return undefined;
            return isAbsolute(configuredPath)
                ? resolve(configuredPath)
                : resolve(workingDirectory, configuredPath);
        },
        argv: process.argv,
    });
}
export async function synchronizeConfiguredServices(syncIntegration, serviceRegistry) {
    const services = serviceRegistry.getAll();
    await Promise.all(Object.entries(services).map(async ([id, config]) => {
        const inspection = await serviceRegistry.inspect(id);
        if (!inspection)
            return;
        syncIntegration({
            id,
            displayName: config.name || id,
            category: 'custom',
            status: inspection.hasPrimaryCredential ? 'healthy' : 'unconfigured',
            enabled: true,
            successCount: 0,
            errorCount: 0,
            meta: {
                authType: config.authType,
                baseUrl: config.baseUrl ?? null,
                hasPrimaryCredential: inspection.hasPrimaryCredential,
                hasWebhookUrl: inspection.hasWebhookUrl,
                hasSigningSecret: inspection.hasSigningSecret,
                hasPublicKey: inspection.hasPublicKey,
                hasAppToken: inspection.hasAppToken,
            },
        }, 'bootstrap.services');
    }));
}
export function restoreRuntimeModel(providerRegistry, savedModel, runtime) {
    const registry = providerRegistry.listModels();
    const modelDef = registry.find((m) => m.registryKey === savedModel);
    if (!modelDef)
        return;
    try {
        const key = modelDef.registryKey;
        providerRegistry.setCurrentModel(key);
        runtime.model = key;
        runtime.provider = modelDef.provider;
    }
    catch (err) {
        logger.warn('Model restore failed', { error: summarizeError(err) });
    }
}
