"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAPIKeys = validateAPIKeys;
exports.loadAIConfig = loadAIConfig;
exports.getAIConfig = getAIConfig;
exports.resetConfigCache = resetConfigCache;
exports.isAIConfigured = isAIConfigured;
exports.getConfigSummary = getConfigSummary;
const dotenv = __importStar(require("dotenv"));
const zod_1 = require("zod");
// Load environment variables
dotenv.config();
/**
 * AI Configuration Schema
 * Validates and structures AI service configuration
 */
const AIConfigSchema = zod_1.z.object({
    openai: zod_1.z.object({
        apiKey: zod_1.z.string().min(1),
        model: zod_1.z.string().default('gpt-4-turbo'),
        maxTokens: zod_1.z.number().default(4096),
        temperature: zod_1.z.number().min(0).max(2).default(0.7),
        retryAttempts: zod_1.z.number().default(3),
        retryDelayMs: zod_1.z.number().default(1000),
        timeout: zod_1.z.number().default(30000), // 30 seconds
    }),
    langchain: zod_1.z.object({
        verbose: zod_1.z.boolean().default(false),
        cacheEnabled: zod_1.z.boolean().default(true),
        cacheTTL: zod_1.z.number().default(3600), // 1 hour in seconds
        maxConcurrency: zod_1.z.number().default(5),
        memoryBufferSize: zod_1.z.number().default(10), // Number of messages to keep in memory
    }),
    rateLimit: zod_1.z.object({
        maxRequestsPerMinute: zod_1.z.number().default(60),
        maxTokensPerMinute: zod_1.z.number().default(90000),
        maxRequestsPerDay: zod_1.z.number().default(10000),
    }),
    monitoring: zod_1.z.object({
        trackTokenUsage: zod_1.z.boolean().default(true),
        logLevel: zod_1.z.enum(['debug', 'info', 'warn', 'error']).default('info'),
        metricsEnabled: zod_1.z.boolean().default(true),
    }),
});
/**
 * Validates API keys on startup
 * Throws error if required keys are missing or invalid
 */
function validateAPIKeys() {
    const openaiKey = process.env.OPENAI_API_KEY;
    if (!openaiKey) {
        throw new Error('OPENAI_API_KEY is required but not found in environment variables');
    }
    // Basic format validation for OpenAI key
    if (!openaiKey.startsWith('sk-')) {
        console.warn('Warning: OPENAI_API_KEY does not start with "sk-". This might be an invalid key format.');
    }
    // Check for optional LangChain-specific keys if needed
    const langchainApiKey = process.env.LANGCHAIN_API_KEY;
    if (langchainApiKey) {
        console.info('LangChain API key detected and will be used for enhanced features');
    }
}
/**
 * Loads and validates AI configuration from environment variables
 * @returns Validated AI configuration object
 */
function loadAIConfig() {
    // Validate API keys first
    validateAPIKeys();
    // Build configuration object from environment variables
    const config = {
        openai: {
            apiKey: process.env.OPENAI_API_KEY,
            model: process.env.OPENAI_MODEL || 'gpt-4-turbo',
            maxTokens: parseInt(process.env.OPENAI_MAX_TOKENS || '4096', 10),
            temperature: parseFloat(process.env.OPENAI_TEMPERATURE || '0.7'),
            retryAttempts: parseInt(process.env.OPENAI_RETRY_ATTEMPTS || '3', 10),
            retryDelayMs: parseInt(process.env.OPENAI_RETRY_DELAY_MS || '1000', 10),
            timeout: parseInt(process.env.OPENAI_TIMEOUT || '30000', 10),
        },
        langchain: {
            verbose: process.env.LANGCHAIN_VERBOSE === 'true',
            cacheEnabled: process.env.LANGCHAIN_CACHE_ENABLED !== 'false',
            cacheTTL: parseInt(process.env.LANGCHAIN_CACHE_TTL || '3600', 10),
            maxConcurrency: parseInt(process.env.LANGCHAIN_MAX_CONCURRENCY || '5', 10),
            memoryBufferSize: parseInt(process.env.LANGCHAIN_MEMORY_BUFFER_SIZE || '10', 10),
        },
        rateLimit: {
            maxRequestsPerMinute: parseInt(process.env.AI_MAX_REQUESTS_PER_MINUTE || '60', 10),
            maxTokensPerMinute: parseInt(process.env.AI_MAX_TOKENS_PER_MINUTE || '90000', 10),
            maxRequestsPerDay: parseInt(process.env.AI_MAX_REQUESTS_PER_DAY || '10000', 10),
        },
        monitoring: {
            trackTokenUsage: process.env.AI_TRACK_TOKEN_USAGE !== 'false',
            logLevel: (process.env.AI_LOG_LEVEL || 'info'),
            metricsEnabled: process.env.AI_METRICS_ENABLED !== 'false',
        },
    };
    // Validate configuration against schema
    try {
        return AIConfigSchema.parse(config);
    }
    catch (error) {
        if (error instanceof zod_1.z.ZodError) {
            throw new Error(`Invalid AI configuration: ${error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`);
        }
        throw error;
    }
}
/**
 * Get singleton instance of AI configuration
 */
let cachedConfig = null;
function getAIConfig() {
    if (!cachedConfig) {
        cachedConfig = loadAIConfig();
    }
    return cachedConfig;
}
/**
 * Reset configuration cache (useful for testing)
 */
function resetConfigCache() {
    cachedConfig = null;
}
/**
 * Check if AI services are properly configured
 */
function isAIConfigured() {
    try {
        validateAPIKeys();
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Get configuration summary for logging
 */
function getConfigSummary() {
    const config = getAIConfig();
    return {
        openai: {
            model: config.openai.model,
            maxTokens: config.openai.maxTokens,
            temperature: config.openai.temperature,
            configured: true,
        },
        langchain: {
            cacheEnabled: config.langchain.cacheEnabled,
            cacheTTL: config.langchain.cacheTTL,
            maxConcurrency: config.langchain.maxConcurrency,
        },
        rateLimit: {
            maxRequestsPerMinute: config.rateLimit.maxRequestsPerMinute,
            maxTokensPerMinute: config.rateLimit.maxTokensPerMinute,
        },
        monitoring: {
            trackTokenUsage: config.monitoring.trackTokenUsage,
            logLevel: config.monitoring.logLevel,
            metricsEnabled: config.monitoring.metricsEnabled,
        },
    };
}
//# sourceMappingURL=ai.config.js.map