import { readFile, writeFile } from 'node:fs/promises';
import { validateName } from './profiles.js';
export function buildPack(profiles, opts = {}) {
    return {
        schema: 1,
        exportedAt: new Date().toISOString(),
        profiles: profiles.map(p => toPackProfile(p, opts.redact ?? false)),
    };
}
function toPackProfile(p, redact) {
    const out = {
        name: p.name,
        provider: p.provider,
        baseUrl: p.baseUrl,
        authType: p.authType,
        apiKey: redact ? '' : p.apiKey,
    };
    if (p.model)
        out.model = p.model;
    if (p.fastModel)
        out.fastModel = p.fastModel;
    return out;
}
export async function writePack(path, pack) {
    await writeFile(path, `${JSON.stringify(pack, null, 2)}\n`, 'utf-8');
}
export async function readPack(path) {
    const raw = await readFile(path, 'utf-8');
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch (e) {
        throw new Error(`包文件不是合法 JSON: ${e.message}`);
    }
    return validatePack(parsed);
}
export function validatePack(input) {
    if (typeof input !== 'object' || input === null) {
        throw new Error('包内容必须是 JSON 对象');
    }
    const obj = input;
    if (obj.schema !== 1) {
        throw new Error(`不支持的 schema: ${String(obj.schema)}（当前仅支持 1）`);
    }
    if (!Array.isArray(obj.profiles)) {
        throw new Error('字段 profiles 缺失或不是数组');
    }
    const profiles = [];
    for (let i = 0; i < obj.profiles.length; i++) {
        profiles.push(validateEntry(obj.profiles[i], i));
    }
    return {
        schema: 1,
        exportedAt: typeof obj.exportedAt === 'string' ? obj.exportedAt : new Date().toISOString(),
        profiles,
    };
}
function validateEntry(input, idx) {
    if (typeof input !== 'object' || input === null) {
        throw new Error(`profiles[${idx}] 不是对象`);
    }
    const o = input;
    const name = expectString(o.name, `profiles[${idx}].name`);
    validateName(name);
    const provider = expectString(o.provider, `profiles[${idx}].provider`);
    const baseUrl = expectString(o.baseUrl, `profiles[${idx}].baseUrl`);
    const authType = o.authType;
    if (authType !== 'api_key' && authType !== 'auth_token') {
        throw new Error(`profiles[${idx}].authType 必须是 "api_key" 或 "auth_token"`);
    }
    const apiKey = typeof o.apiKey === 'string' ? o.apiKey : '';
    const out = { name, provider, baseUrl, authType, apiKey };
    if (typeof o.model === 'string' && o.model)
        out.model = o.model;
    if (typeof o.fastModel === 'string' && o.fastModel)
        out.fastModel = o.fastModel;
    return out;
}
function expectString(v, field) {
    if (typeof v !== 'string' || v.length === 0) {
        throw new Error(`${field} 必须是非空字符串`);
    }
    return v;
}
export function packProfileToProfile(pp) {
    const out = {
        name: pp.name,
        provider: pp.provider,
        baseUrl: pp.baseUrl,
        authType: pp.authType,
        apiKey: pp.apiKey,
        createdAt: new Date().toISOString(),
    };
    if (pp.model)
        out.model = pp.model;
    if (pp.fastModel)
        out.fastModel = pp.fastModel;
    return out;
}
//# sourceMappingURL=profile-pack.js.map