const fs = require('fs'); const path = require('path'); const db = require('../db/database'); var LOG_DIR = path.join(__dirname, '../../data/logs'); if (!fs.existsSync(LOG_DIR)) { fs.mkdirSync(LOG_DIR, { recursive: true }); } function estimateCost(model, inputTokens, outputTokens) { if (!model || !inputTokens) return 0; var rates = { 'google/gemini-2.5-flash': { input: 0.075, output: 0.30 }, 'google/gemini-2.5-pro': { input: 1.25, output: 5.00 }, 'deepseek/deepseek-chat-v3-0324': { input: 0.14, output: 0.28 }, 'deepseek/deepseek-r1': { input: 0.55, output: 2.19 }, 'deepseek/deepseek-r1:free': { input: 0, output: 0 }, 'qwen/qwen3-30b-a3b:free': { input: 0, output: 0 }, 'anthropic/vendor-model-sonnet-4': { input: 3.00, output: 15.00 }, 'anthropic/vendor-model-3-haiku': { input: 0.25, output: 1.25 }, 'openai/gpt-4.1-mini': { input: 0.40, output: 1.60 }, 'meta-llama/llama-3.3-70b-instruct': { input: 0.10, output: 0.16 } }; var rate = rates[model] || { input: 0.50, output: 1.00 }; return ((inputTokens / 1000000) * rate.input) + (((outputTokens || 0) / 1000000) * rate.output); } var logger = { audit: function(userId, action, details, req, extra) { var e = extra || {}; db.run( 'INSERT INTO audit_log (user_id, action, category, details, ip_address, user_agent, model_used, tokens_used, duration_ms, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [ userId || null, action, e.category || 'general', typeof details === 'string' ? details : JSON.stringify(details), req ? (req.ip || null) : null, req ? (req.headers['user-agent'] || '').substring(0, 255) : null, e.model || null, e.tokens || null, e.duration || null, e.status || 'success' ] ).catch(function(err) { console.error('[Logger] Audit failed:', err.message); }); }, apiCall: function(userId, endpoint, data) { var d = data || {}; var cost = estimateCost(d.model, d.tokensInput, d.tokensOutput); db.run( 'INSERT INTO api_log (user_id, endpoint, method, status_code, request_size, response_size, model_used, tokens_input, tokens_output, cost_estimate, duration_ms, ip_address, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [ userId || null, endpoint, d.method || 'POST', d.statusCode || 200, d.requestSize || 0, d.responseSize || 0, d.model || null, d.tokensInput || 0, d.tokensOutput || 0, cost, d.duration || 0, d.ip || null, d.error || null ] ).catch(function(err) { console.error('[Logger] API log failed:', err.message); }); }, access: function(userId, action, req, success) { db.run( 'INSERT INTO access_log (user_id, action, ip_address, user_agent, success) VALUES (?, ?, ?, ?, ?)', [ userId || null, action, req ? (req.ip || null) : null, req ? (req.headers['user-agent'] || '').substring(0, 255) : null, success ? true : false ] ).catch(function(err) { console.error('[Logger] Access log failed:', err.message); }); }, file: function(level, message, data) { try { var now = new Date(); var date = now.toISOString().split('T')[0]; var logFile = path.join(LOG_DIR, date + '.log'); var line = '[' + now.toISOString() + '] [' + level.toUpperCase() + '] ' + message; if (data) line += ' | ' + (typeof data === 'string' ? data : JSON.stringify(data)); line += '\n'; fs.appendFileSync(logFile, line); if (level === 'error') console.error(line.trim()); } catch (e) {} }, info: function(msg, data) { this.file('info', msg, data); }, warn: function(msg, data) { this.file('warn', msg, data); }, error: function(msg, data) { this.file('error', msg, data); }, getAuditLogs: function(userId, limit) { return db.all('SELECT * FROM audit_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?', [userId, limit || 100]); }, getApiLogs: function(userId, limit) { return db.all('SELECT * FROM api_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?', [userId, limit || 100]); }, getAccessLogs: function(userId, limit) { return db.all('SELECT * FROM access_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?', [userId, limit || 100]); }, getUsageSummary: function(userId, days) { var since = new Date(Date.now() - (days || 30) * 86400000).toISOString(); return db.all( 'SELECT COUNT(*) as total_calls, SUM(tokens_input) as total_input_tokens, SUM(tokens_output) as total_output_tokens, SUM(cost_estimate) as total_estimated_cost, AVG(duration_ms) as avg_duration_ms, model_used, endpoint FROM api_log WHERE user_id = ? AND timestamp > ? GROUP BY model_used, endpoint ORDER BY total_calls DESC', [userId, since] ); } }; console.log('✅ Logger initialized'); module.exports = logger;