/**
 * Provider 配置管理
 *
 * Provider = AgentType + 名称 + 环境变量(连接配置) + 运行参数
 *
 * 数据结构: { providers: Provider[] }
 * - 内置默认配置 (default-providers.json)
 * - 用户自定义 ($AGENT_TOWER_DATA_DIR/providers.json)
 * - 合并策略: 内置 providers 始终存在，用户可新增或覆盖内置 provider 的配置
 */
import * as fs from 'fs';
import * as path from 'path';
import { randomUUID } from 'crypto';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
// ─── Defaults ────────────────────────────────────────────────────
const require = createRequire(import.meta.url);
const defaultProvidersJson = require('./default-providers.json');
const DEFAULT_PROVIDERS = defaultProvidersJson;
// ─── State ───────────────────────────────────────────────────────
let cachedProviders = null;
// ─── User data path ─────────────────────────────────────────────
function getUserProvidersPath() {
    if (process.env.AGENT_TOWER_DATA_DIR) {
        return path.join(process.env.AGENT_TOWER_DATA_DIR, 'providers.json');
    }
    const __dirname = path.dirname(fileURLToPath(import.meta.url));
    const serverRoot = path.resolve(__dirname, '..', '..');
    return path.join(serverRoot, 'data', 'providers.json');
}
// ─── Core functions ──────────────────────────────────────────────
/**
 * 合并内置 + 用户自定义 providers
 * - 用户可新增 provider
 * - 用户可通过相同 id 覆盖内置 provider 的 config/env/name
 * - 内置 provider 不会被删除
 */
function mergeProviders(builtIns, userProviders) {
    const result = [];
    const userMap = new Map(userProviders.map(p => [p.id, p]));
    // 内置 providers：如果用户有同 id 覆盖，则合并
    for (const builtIn of builtIns) {
        const userOverride = userMap.get(builtIn.id);
        if (userOverride) {
            result.push({
                ...builtIn,
                ...userOverride,
                builtIn: true, // 始终标记为内置
            });
            userMap.delete(builtIn.id);
        }
        else {
            result.push({ ...builtIn });
        }
    }
    // 用户新增的 providers
    for (const userProvider of userMap.values()) {
        result.push({ ...userProvider, builtIn: false });
    }
    return result;
}
function toPersistedProvider(provider) {
    const normalized = {
        id: provider.id,
        name: provider.name,
        agentType: provider.agentType,
        env: { ...(provider.env ?? {}) },
        config: { ...(provider.config ?? {}) },
        isDefault: !!provider.isDefault,
    };
    if (provider.settings?.trim()) {
        normalized.settings = provider.settings;
    }
    if (provider.createdAt) {
        normalized.createdAt = provider.createdAt;
    }
    return normalized;
}
function toComparableProvider(provider) {
    const { createdAt, ...rest } = toPersistedProvider(provider);
    return rest;
}
function normalizeProviderDefaults(providers) {
    const lastDefaultIndexByType = new Map();
    providers.forEach((provider, index) => {
        if (provider.isDefault) {
            lastDefaultIndexByType.set(String(provider.agentType), index);
        }
    });
    return providers.map((provider, index) => {
        const lastDefaultIndex = lastDefaultIndexByType.get(String(provider.agentType));
        if (lastDefaultIndex === undefined)
            return provider;
        return {
            ...provider,
            isDefault: lastDefaultIndex === index,
        };
    });
}
function areProvidersEquivalent(a, b) {
    return JSON.stringify(toComparableProvider(a)) === JSON.stringify(toComparableProvider(b));
}
function getBuiltInProviderById(id) {
    const provider = DEFAULT_PROVIDERS.providers.find(p => p.id === id);
    if (!provider)
        return null;
    return { ...structuredClone(provider), builtIn: true };
}
/**
 * 提取用户自定义部分（与默认不同的 + 新增的）
 */
function extractUserProviders(merged) {
    const builtInIds = new Set(DEFAULT_PROVIDERS.providers.map(p => p.id));
    const userProviders = [];
    for (const provider of merged) {
        if (!builtInIds.has(provider.id)) {
            // 用户新增的
            userProviders.push(provider);
        }
        else {
            // 内置的，检查是否有修改
            const defaultProvider = DEFAULT_PROVIDERS.providers.find(p => p.id === provider.id);
            if (defaultProvider && JSON.stringify(defaultProvider) !== JSON.stringify({ ...provider, builtIn: true })) {
                // 有修改，保存覆盖
                const { builtIn, ...rest } = provider;
                userProviders.push(rest);
            }
        }
    }
    return userProviders;
}
/**
 * 加载 providers（内置 + 用户合并）
 */
export function loadProviders() {
    const builtIns = structuredClone(DEFAULT_PROVIDERS.providers).map(p => ({ ...p, builtIn: true }));
    const userPath = getUserProvidersPath();
    let userProviders = [];
    try {
        if (fs.existsSync(userPath)) {
            const content = fs.readFileSync(userPath, 'utf-8');
            const data = JSON.parse(content);
            userProviders = data.providers ?? [];
        }
    }
    catch (e) {
        console.error('[Providers] Failed to load user providers.json:', e);
    }
    cachedProviders = mergeProviders(builtIns, userProviders);
    // 旧数据兼容：settings 从 Record<string, unknown> 迁移为 string
    for (const p of cachedProviders) {
        if (p.settings && typeof p.settings === 'object') {
            p.settings = JSON.stringify(p.settings, null, 2);
        }
    }
    return cachedProviders;
}
/**
 * 获取所有 providers（带缓存）
 */
export function getAllProviders() {
    if (!cachedProviders) {
        return loadProviders();
    }
    return cachedProviders;
}
/**
 * 重新加载
 */
export function reloadProviders() {
    cachedProviders = null;
    return loadProviders();
}
/**
 * 根据 ID 获取 provider
 */
export function getProviderById(id) {
    return getAllProviders().find(p => p.id === id) ?? null;
}
/**
 * 根据 agentType 获取所有 providers
 */
export function getProvidersByAgentType(agentType) {
    return getAllProviders().filter(p => p.agentType === agentType);
}
/**
 * 获取某个 agentType 的默认 provider
 */
export function getDefaultProvider(agentType) {
    const providers = getProvidersByAgentType(agentType);
    return providers.find(p => p.isDefault) ?? providers[0] ?? null;
}
export function getUserProviders() {
    return structuredClone(extractUserProviders(getAllProviders()));
}
export function createProviderBackup() {
    return {
        version: 1,
        kind: 'provider-backup',
        exportedAt: new Date().toISOString(),
        mode: 'full',
        providers: getUserProviders().map(toPersistedProvider),
    };
}
export function previewProviderImport(backup) {
    const existingProviders = getAllProviders();
    const existingById = new Map(existingProviders.map(provider => [provider.id, provider]));
    const items = [];
    const summary = {
        create: 0,
        overwrite: 0,
        skip: 0,
    };
    for (const rawProvider of backup.providers) {
        const incoming = toPersistedProvider(rawProvider);
        const existing = existingById.get(incoming.id) ?? null;
        let action;
        if (!existing) {
            action = 'CREATE';
            summary.create += 1;
        }
        else if (areProvidersEquivalent(existing, incoming)) {
            action = 'SKIP';
            summary.skip += 1;
        }
        else {
            action = 'OVERWRITE';
            summary.overwrite += 1;
        }
        items.push({
            action,
            incoming,
            existing,
        });
    }
    return { summary, items };
}
export function importProvidersFromBackup(backup) {
    const preview = previewProviderImport(backup);
    const providers = [...getAllProviders()];
    for (const item of preview.items) {
        if (item.action === 'SKIP')
            continue;
        const incoming = toPersistedProvider(item.incoming);
        const index = providers.findIndex(provider => provider.id === incoming.id);
        if (index === -1) {
            providers.push({
                ...incoming,
                builtIn: false,
            });
            continue;
        }
        providers[index] = {
            ...providers[index],
            ...incoming,
            builtIn: providers[index].builtIn ?? false,
        };
    }
    saveProviders(normalizeProviderDefaults(providers));
    return {
        summary: preview.summary,
        providers: getAllProviders(),
    };
}
// ─── Persistence ─────────────────────────────────────────────────
function saveProviders(providers) {
    const userProviders = extractUserProviders(providers).map(toPersistedProvider);
    const userPath = getUserProvidersPath();
    const dir = path.dirname(userPath);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    const data = { providers: userProviders };
    fs.writeFileSync(userPath, JSON.stringify(data, null, 2), 'utf-8');
    // 更新缓存
    cachedProviders = providers;
}
// ─── CRUD ────────────────────────────────────────────────────────
export function createProvider(data) {
    const providers = [...getAllProviders()];
    const provider = {
        ...data,
        id: randomUUID().slice(0, 8),
        builtIn: false,
        createdAt: new Date().toISOString(),
    };
    // 如果设为默认，取消同类型其他默认
    if (provider.isDefault) {
        for (const p of providers) {
            if (p.agentType === provider.agentType) {
                p.isDefault = false;
            }
        }
    }
    providers.push(provider);
    saveProviders(providers);
    return provider;
}
export function updateProvider(id, data) {
    const providers = [...getAllProviders()];
    const index = providers.findIndex(p => p.id === id);
    if (index === -1)
        return null;
    const updated = { ...providers[index], ...data };
    // 如果设为默认，取消同类型其他默认
    if (data.isDefault) {
        for (const p of providers) {
            if (p.agentType === updated.agentType && p.id !== id) {
                p.isDefault = false;
            }
        }
    }
    providers[index] = updated;
    saveProviders(providers);
    return updated;
}
export function deleteProvider(id) {
    const providers = [...getAllProviders()];
    const provider = providers.find(p => p.id === id);
    if (!provider)
        return false;
    if (provider.builtIn) {
        const builtInProvider = getBuiltInProviderById(id);
        const isOverridden = builtInProvider ? !areProvidersEquivalent(provider, builtInProvider) : false;
        if (!builtInProvider || !isOverridden) {
            throw new Error(`Cannot delete built-in provider '${provider.name}'`);
        }
        const restored = providers.map(p => (p.id === id ? builtInProvider : p));
        saveProviders(normalizeProviderDefaults(restored));
        return true;
    }
    const filtered = providers.filter(p => p.id !== id);
    saveProviders(normalizeProviderDefaults(filtered));
    return true;
}
export function canDeleteProvider(provider) {
    if (!provider.builtIn)
        return true;
    const builtInProvider = getBuiltInProviderById(provider.id);
    if (!builtInProvider)
        return false;
    return !areProvidersEquivalent(provider, builtInProvider);
}
/**
 * 获取内置默认 providers（不含用户自定义）
 */
export function getDefaultProviders() {
    return structuredClone(DEFAULT_PROVIDERS.providers).map(p => ({ ...p, builtIn: true }));
}
//# sourceMappingURL=providers.js.map