Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/agentwolf27_carbonwise.json
T

1 line
54 KiB
JSON

{"repo": "agentwolf27/carbonwise", "files": {"src/lib/ai-carbon-enhancer.ts": {"57b9fe6ae68ca9b3b0a7f7c7e92663d74206c7ee": {"t": 1785745596.5960476, "n": 13924, "h": "2cdf03d9008545bd", "c": "// AI-Enhanced Carbon Footprint Calculator\n// Integrates DeepSeek V3 via OpenRouter API for improved accuracy and intelligence\n\nimport OpenAI from 'openai';\n\ninterface CarbonCalculationInput {\n url: string;\n domain: string;\n pageTitle: string;\n timeOnPage: number;\n scrollDepth: number;\n clickCount: number;\n deviceType: string;\n networkType: string;\n location: {\n lat: number;\n lng: number;\n country: string;\n };\n userAgent: string;\n timestamp: Date;\n}\n\ninterface AIEnhancedResult {\n carbonEmission: number;\n activityType: string;\n confidence: number;\n breakdown: {\n deviceEnergy: number;\n networkTransfer: number;\n serverProcessing: number;\n aiProcessing?: number;\n };\n insights: string[];\n recommendations: string[];\n}\n\nexport class AIEnhancedCarbonCalculator {\n private openrouterClient: OpenAI;\n private climatiqApiKey: string;\n private websiteEnergyDb: any[] = [];\n private deviceEnergyDb: any[] = [];\n\n constructor() {\n this.openrouterClient = new OpenAI({\n apiKey: process.env.DEEPSEEK_API_KEY, // OpenRouter API key\n baseURL: 'https://openrouter.ai/api/v1',\n });\n this.climatiqApiKey = process.env.CLIMATIQ_API_KEY || '';\n this.loadDatabases();\n }\n\n private loadDatabases() {\n // Load our training datasets\n try {\n this.websiteEnergyDb = require('../../training-data/website-energy-database.json');\n this.deviceEnergyDb = require('../../training-data/device-energy-consumption.json');\n } catch (error) {\n console.warn('Training datasets not found, using fallback data');\n this.websiteEnergyDb = [];\n this.deviceEnergyDb = [];\n }\n }\n\n // Main AI-enhanced calculation method\n async calculateEnhancedCarbon(input: CarbonCalculationInput): Promise<AIEnhancedResult> {\n try {\n // Step 1: Basic calculation using our database\n const baseCalculation = this.calculateBaseCarbon(input);\n \n // Step 2: AI-enhanced activity classification\n const activityClassification = await this.classifyActivityWithAI(input);\n \n // Step 3: Real-time emission factors from Climatiq\n const realTimeFactors = await this.getRealTimeEmissionFactors(input.location.country);\n \n // Step 4: AI-generated insights and recommendations\n const insights = await this.generateAIInsights(input, baseCalculation);\n \n // Step 5: Combine all data for final result\n const enhancedResult = this.combineCalculations(\n baseCalculation,\n activityClassification,\n realTimeFactors,\n insights\n );\n\n return enhancedResult;\n } catch (error) {\n console.error('AI-enhanced calculation failed:', error);\n // Fallback to basic calculation\n return this.getFallbackCalculation(input);\n }\n }\n\n // Basic carbon calculation using our datasets\n private calculateBaseCarbon(input: CarbonCalculationInput) {\n // Find website in our database\n const websiteData = this.websiteEnergyDb.find(site => \n input.domain.includes(site.domain.replace('www.', ''))\n );\n\n // Find device energy consumption\n const deviceData = this.deviceEnergyDb.find(device => \n input.deviceType.toLowerCase().includes(device.category)\n );\n\n // Calculate base emissions\n const websiteEmission = websiteData ? websiteData.co2_per_visit_g : 3.5; // Default\n const deviceEmission = deviceData ? \n (deviceData.browsing_watts * input.timeOnPage / 3600 * 0.709) : 2.1; // Default\n \n const networkEmission = this.calculateNetworkEmission(input);\n \n return {\n total: websiteEmission + deviceEmission + networkEmission,\n website: websiteEmission,\n device: deviceEmission,\n network: networkEmission,\n confidence: websiteData && deviceData ? 0.8 : 0.6\n };\n }\n\n // AI-powered activity classification using DeepSeek V3 via OpenRouter\n private async classifyActivityWithAI(input: CarbonCalculationInput) {\n const prompt = `\n Analyze this web activity and classify it for carbon footprint calculation:\n \n URL: ${input.url}\n Domain: ${input.domain}\n Page Title: ${input.pageTitle}\n Time on Page: ${input.timeOnPage}s\n Scroll Depth: ${input.scrollDepth}%\n Clicks: ${input.clickCount}\n \n Classify this activity into one of these categories:\n 1. SEARCH - Web searches\n 2. SOCIAL_MEDIA - Social platforms, messaging\n 3. STREAMING - Video/audio streaming\n 4. SHOPPING - E-commerce, browsing products\n 5. AI_INTERACTION - ChatGPT, Claude, AI tools\n 6. WORK - Productivity, email, documents\n 7. NEWS - Reading news, articles\n 8. GAMING - Online games\n 9. OTHER - Anything else\n \n Also estimate the carbon intensity (LOW/MEDIUM/HIGH) based on:\n - Page complexity and resource usage\n - User interaction level\n - Likely backend processing requirements\n \n Respond with ONLY a JSON object (no markdown formatting): {\"category\": \"...\", \"intensity\": \"...\", \"reasoning\": \"...\"}\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 200,\n temperature: 0.3\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n category: result.category || 'OTHER',\n intensity: result.intensity || 'MEDIUM',\n reasoning: result.reasoning || '',\n confidence: 0.85\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) classification failed:', error);\n return {\n category: this.fallbackClassification(input.domain),\n intensity: 'MEDIUM',\n reasoning: 'Fallback classification',\n confidence: 0.5\n };\n }\n }\n\n // Get real-time grid-electricity emission factor (kg CO2e / kWh) from\n // Climatiq's Search API for the user's country/region.\n // Docs: https://www.climatiq.io/docs/api-reference/search\n private async getRealTimeEmissionFactors(country: string) {\n const fallback = this.fallbackElectricityFactor(country);\n\n if (!this.climatiqApiKey) {\n return { electricityFactor: fallback, confidence: 0.3 };\n }\n\n try {\n const region = (country || 'US').toUpperCase();\n const params = new URLSearchParams({\n query: 'electricity supply grid',\n region,\n results_per_page: '1',\n data_version: '^6',\n });\n\n const response = await fetch(`https://api.climatiq.io/data/v1/search?${params.toString()}`, {\n method: 'GET',\n headers: { Authorization: `Bearer ${this.climatiqApiKey}` },\n });\n\n if (response.ok) {\n const data = await response.json();\n const factor = data?.results?.[0]?.factor;\n if (typeof factor === 'number' && factor > 0) {\n return { electricityFactor: factor, confidence: 0.9 };\n }\n // API responded but had no usable grid factor for this region.\n return { electricityFactor: fallback, confidence: 0.5 };\n }\n\n console.error('Climatiq API error:', response.status, await response.text());\n } catch (error) {\n console.error('Climatiq API failed:', error instanceof Error ? error.message : error);\n }\n\n return { electricityFactor: fallback, confidence: 0.4 };\n }\n\n // Static per-country grid intensity (kg CO2e / kWh) used when Climatiq\n // is unavailable or returns no match.\n private fallbackElectricityFactor(country: string): number {\n const countryFactors: { [key: string]: number } = {\n US: 0.709, UK: 0.233, GB: 0.233, DE: 0.401, FR: 0.056,\n CA: 0.13, AU: 0.81, IN: 0.708, CN: 0.555, JP: 0.474,\n };\n return countryFactors[(country || 'US').toUpperCase()] || 0.709;\n }\n\n // Generate AI insights and recommendations using DeepSeek V3\n private async generateAIInsights(input: CarbonCalculationInput, calculation: any) {\n const prompt = `\n Based on this web activity carbon calculation, provide insights and recommendations:\n \n Activity: ${input.domain} for ${input.timeOnPage}s\n Carbon Emission: ${calculation.total.toFixed(2)}g CO2\n Device: ${input.deviceType}\n \n Provide:\n 1. 2-3 brief insights about this activity's environmental impact\n 2. 2-3 actionable recommendations to reduce emissions\n \n Keep responses concise and practical. Focus on digital behavior changes.\n \n Respond with ONLY a JSON object (no markdown formatting): {\n \"insights\": [\"insight1\", \"insight2\"],\n \"recommendations\": [\"rec1\", \"rec2\"]\n }\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 300,\n temperature: 0.7\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n insights: result.insights || [],\n recommendations: result.recommendations || []\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) insights generation failed:', error);\n return {\n insights: ['This activity contributed to your digital carbon footprint'],\n recommendations: ['Consider reducing time on high-emission websites']\n };\n }\n }\n\n // Combine all calculations and AI insights\n private combineCalculations(\n baseCalculation: any,\n activityClassification: any,\n realTimeFactors: any,\n insights: any\n ): AIEnhancedResult {\n // Adjust base calculation based on AI classification\n const intensityMultipliers = {\n 'LOW': 0.7,\n 'MEDIUM': 1.0,\n 'HIGH': 1.4\n };\n\n const intensityMultiplier = intensityMultipliers[activityClassification.intensity as keyof typeof intensityMultipliers] || 1.0;\n const adjustedEmission = baseCalculation.total * intensityMultiplier;\n\n // Apply real-time electricity factors\n const deviceAdjustedEmission = baseCalculation.device * (realTimeFactors.electricityFactor / 0.709);\n \n const finalEmission = baseCalculation.website + deviceAdjustedEmission + baseCalculation.network;\n\n return {\n carbonEmission: Math.round(finalEmission * 100) / 100,\n activityType: activityClassification.category,\n confidence: Math.min(\n baseCalculation.confidence,\n activityClassification.confidence,\n realTimeFactors.confidence\n ),\n breakdown: {\n deviceEnergy: Math.round(deviceAdjustedEmission * 100) / 100,\n networkTransfer: Math.round(baseCalculation.network * 100) / 100,\n serverProcessing: Math.round(baseCalculation.website * 100) / 100,\n aiProcessing: activityClassification.category === 'AI_INTERACTION' ? \n Math.round(finalEmission * 0.3 * 100) / 100 : undefined\n },\n insights: insights.insights,\n recommendations: insights.recommendations\n };\n }\n\n // Helper methods\n private calculateNetworkEmission(input: CarbonCalculationInput): number {\n // Estimate data transfer based on time on page and activity\n const estimatedDataMB = Math.min(input.timeOnPage * 0.1, 50); // Max 50MB\n \n const networkEmissionFactors = {\n 'wifi': 0.05,\n '4g': 0.18,\n '5g': 0.08,\n 'ethernet': 0.03\n };\n\n const factor = networkEmissionFactors[input.networkType as keyof typeof networkEmissionFactors] || 0.12;\n return estimatedDataMB * factor;\n }\n\n private fallbackClassification(domain: string): string {\n if (domain.includes('google') || domain.includes('bing')) return 'SEARCH';\n if (domain.includes('youtube') || domain.includes('netflix')) return 'STREAMING';\n if (domain.includes('facebook') || domain.includes('twitter')) return 'SOCIAL_MEDIA';\n if (domain.includes('amazon') || domain.includes('shop')) return 'SHOPPING';\n if (domain.includes('openai') || domain.includes('claude')) return 'AI_INTERACTION';\n return 'OTHER';\n }\n\n private extractElectricityFactor(data: any, country: string): number {\n // Extract electricity emission factor from Climatiq response\n // This is a simplified implementation\n const countryFactors: { [key: string]: number } = {\n 'US': 0.709,\n 'UK': 0.233,\n 'DE': 0.401,\n 'FR': 0.056,\n 'CA': 0.130,\n 'AU': 0.81\n };\n \n return countryFactors[country] || 0.709;\n }\n\n private getFallbackCalculation(input: CarbonCalculationInput): AIEnhancedResult {\n return {\n carbonEmission: 3.5,\n activityType: 'OTHER',\n confidence: 0.3,\n breakdown: {\n deviceEnergy: 1.5,\n networkTransfer: 1.0,\n serverProcessing: 1.0\n },\n insights: ['Basic calculation used due to AI service unavailability'],\n recommendations: ['Enable AI features for personalized recommendations']\n };\n }\n}\n\n// Enhanced API endpoint integration\nexport async function enhancedCarbonCalculation(\n url: string,\n timeOnPage: number,\n userContext: any\n) {\n const calculator = new AIEnhancedCarbonCalculator();\n \n const input: CarbonCalculationInput = {\n url,\n domain: new URL(url).hostname,\n pageTitle: userContext.pageTitle || '',\n timeOnPage,\n scrollDepth: userContext.scrollDepth || 0,\n clickCount: userContext.clickCount || 0,\n deviceType: userContext.deviceType || 'laptop',\n networkType: userContext.networkType || 'wifi',\n location: userContext.location || { lat: 37.7749, lng: -122.4194, country: 'US' },\n userAgent: userContext.userAgent || '',\n timestamp: new Date()\n };\n\n return await calculator.calculateEnhancedCarbon(input);\n} "}, "9f0ba06bd174d512124374fba9a5960bfe00157b": {"t": 1785754620.7900517, "n": 13924, "h": "2cdf03d9008545bd", "c": "// AI-Enhanced Carbon Footprint Calculator\n// Integrates DeepSeek V3 via OpenRouter API for improved accuracy and intelligence\n\nimport OpenAI from 'openai';\n\ninterface CarbonCalculationInput {\n url: string;\n domain: string;\n pageTitle: string;\n timeOnPage: number;\n scrollDepth: number;\n clickCount: number;\n deviceType: string;\n networkType: string;\n location: {\n lat: number;\n lng: number;\n country: string;\n };\n userAgent: string;\n timestamp: Date;\n}\n\ninterface AIEnhancedResult {\n carbonEmission: number;\n activityType: string;\n confidence: number;\n breakdown: {\n deviceEnergy: number;\n networkTransfer: number;\n serverProcessing: number;\n aiProcessing?: number;\n };\n insights: string[];\n recommendations: string[];\n}\n\nexport class AIEnhancedCarbonCalculator {\n private openrouterClient: OpenAI;\n private climatiqApiKey: string;\n private websiteEnergyDb: any[] = [];\n private deviceEnergyDb: any[] = [];\n\n constructor() {\n this.openrouterClient = new OpenAI({\n apiKey: process.env.DEEPSEEK_API_KEY, // OpenRouter API key\n baseURL: 'https://openrouter.ai/api/v1',\n });\n this.climatiqApiKey = process.env.CLIMATIQ_API_KEY || '';\n this.loadDatabases();\n }\n\n private loadDatabases() {\n // Load our training datasets\n try {\n this.websiteEnergyDb = require('../../training-data/website-energy-database.json');\n this.deviceEnergyDb = require('../../training-data/device-energy-consumption.json');\n } catch (error) {\n console.warn('Training datasets not found, using fallback data');\n this.websiteEnergyDb = [];\n this.deviceEnergyDb = [];\n }\n }\n\n // Main AI-enhanced calculation method\n async calculateEnhancedCarbon(input: CarbonCalculationInput): Promise<AIEnhancedResult> {\n try {\n // Step 1: Basic calculation using our database\n const baseCalculation = this.calculateBaseCarbon(input);\n \n // Step 2: AI-enhanced activity classification\n const activityClassification = await this.classifyActivityWithAI(input);\n \n // Step 3: Real-time emission factors from Climatiq\n const realTimeFactors = await this.getRealTimeEmissionFactors(input.location.country);\n \n // Step 4: AI-generated insights and recommendations\n const insights = await this.generateAIInsights(input, baseCalculation);\n \n // Step 5: Combine all data for final result\n const enhancedResult = this.combineCalculations(\n baseCalculation,\n activityClassification,\n realTimeFactors,\n insights\n );\n\n return enhancedResult;\n } catch (error) {\n console.error('AI-enhanced calculation failed:', error);\n // Fallback to basic calculation\n return this.getFallbackCalculation(input);\n }\n }\n\n // Basic carbon calculation using our datasets\n private calculateBaseCarbon(input: CarbonCalculationInput) {\n // Find website in our database\n const websiteData = this.websiteEnergyDb.find(site => \n input.domain.includes(site.domain.replace('www.', ''))\n );\n\n // Find device energy consumption\n const deviceData = this.deviceEnergyDb.find(device => \n input.deviceType.toLowerCase().includes(device.category)\n );\n\n // Calculate base emissions\n const websiteEmission = websiteData ? websiteData.co2_per_visit_g : 3.5; // Default\n const deviceEmission = deviceData ? \n (deviceData.browsing_watts * input.timeOnPage / 3600 * 0.709) : 2.1; // Default\n \n const networkEmission = this.calculateNetworkEmission(input);\n \n return {\n total: websiteEmission + deviceEmission + networkEmission,\n website: websiteEmission,\n device: deviceEmission,\n network: networkEmission,\n confidence: websiteData && deviceData ? 0.8 : 0.6\n };\n }\n\n // AI-powered activity classification using DeepSeek V3 via OpenRouter\n private async classifyActivityWithAI(input: CarbonCalculationInput) {\n const prompt = `\n Analyze this web activity and classify it for carbon footprint calculation:\n \n URL: ${input.url}\n Domain: ${input.domain}\n Page Title: ${input.pageTitle}\n Time on Page: ${input.timeOnPage}s\n Scroll Depth: ${input.scrollDepth}%\n Clicks: ${input.clickCount}\n \n Classify this activity into one of these categories:\n 1. SEARCH - Web searches\n 2. SOCIAL_MEDIA - Social platforms, messaging\n 3. STREAMING - Video/audio streaming\n 4. SHOPPING - E-commerce, browsing products\n 5. AI_INTERACTION - ChatGPT, Claude, AI tools\n 6. WORK - Productivity, email, documents\n 7. NEWS - Reading news, articles\n 8. GAMING - Online games\n 9. OTHER - Anything else\n \n Also estimate the carbon intensity (LOW/MEDIUM/HIGH) based on:\n - Page complexity and resource usage\n - User interaction level\n - Likely backend processing requirements\n \n Respond with ONLY a JSON object (no markdown formatting): {\"category\": \"...\", \"intensity\": \"...\", \"reasoning\": \"...\"}\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 200,\n temperature: 0.3\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n category: result.category || 'OTHER',\n intensity: result.intensity || 'MEDIUM',\n reasoning: result.reasoning || '',\n confidence: 0.85\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) classification failed:', error);\n return {\n category: this.fallbackClassification(input.domain),\n intensity: 'MEDIUM',\n reasoning: 'Fallback classification',\n confidence: 0.5\n };\n }\n }\n\n // Get real-time grid-electricity emission factor (kg CO2e / kWh) from\n // Climatiq's Search API for the user's country/region.\n // Docs: https://www.climatiq.io/docs/api-reference/search\n private async getRealTimeEmissionFactors(country: string) {\n const fallback = this.fallbackElectricityFactor(country);\n\n if (!this.climatiqApiKey) {\n return { electricityFactor: fallback, confidence: 0.3 };\n }\n\n try {\n const region = (country || 'US').toUpperCase();\n const params = new URLSearchParams({\n query: 'electricity supply grid',\n region,\n results_per_page: '1',\n data_version: '^6',\n });\n\n const response = await fetch(`https://api.climatiq.io/data/v1/search?${params.toString()}`, {\n method: 'GET',\n headers: { Authorization: `Bearer ${this.climatiqApiKey}` },\n });\n\n if (response.ok) {\n const data = await response.json();\n const factor = data?.results?.[0]?.factor;\n if (typeof factor === 'number' && factor > 0) {\n return { electricityFactor: factor, confidence: 0.9 };\n }\n // API responded but had no usable grid factor for this region.\n return { electricityFactor: fallback, confidence: 0.5 };\n }\n\n console.error('Climatiq API error:', response.status, await response.text());\n } catch (error) {\n console.error('Climatiq API failed:', error instanceof Error ? error.message : error);\n }\n\n return { electricityFactor: fallback, confidence: 0.4 };\n }\n\n // Static per-country grid intensity (kg CO2e / kWh) used when Climatiq\n // is unavailable or returns no match.\n private fallbackElectricityFactor(country: string): number {\n const countryFactors: { [key: string]: number } = {\n US: 0.709, UK: 0.233, GB: 0.233, DE: 0.401, FR: 0.056,\n CA: 0.13, AU: 0.81, IN: 0.708, CN: 0.555, JP: 0.474,\n };\n return countryFactors[(country || 'US').toUpperCase()] || 0.709;\n }\n\n // Generate AI insights and recommendations using DeepSeek V3\n private async generateAIInsights(input: CarbonCalculationInput, calculation: any) {\n const prompt = `\n Based on this web activity carbon calculation, provide insights and recommendations:\n \n Activity: ${input.domain} for ${input.timeOnPage}s\n Carbon Emission: ${calculation.total.toFixed(2)}g CO2\n Device: ${input.deviceType}\n \n Provide:\n 1. 2-3 brief insights about this activity's environmental impact\n 2. 2-3 actionable recommendations to reduce emissions\n \n Keep responses concise and practical. Focus on digital behavior changes.\n \n Respond with ONLY a JSON object (no markdown formatting): {\n \"insights\": [\"insight1\", \"insight2\"],\n \"recommendations\": [\"rec1\", \"rec2\"]\n }\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 300,\n temperature: 0.7\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n insights: result.insights || [],\n recommendations: result.recommendations || []\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) insights generation failed:', error);\n return {\n insights: ['This activity contributed to your digital carbon footprint'],\n recommendations: ['Consider reducing time on high-emission websites']\n };\n }\n }\n\n // Combine all calculations and AI insights\n private combineCalculations(\n baseCalculation: any,\n activityClassification: any,\n realTimeFactors: any,\n insights: any\n ): AIEnhancedResult {\n // Adjust base calculation based on AI classification\n const intensityMultipliers = {\n 'LOW': 0.7,\n 'MEDIUM': 1.0,\n 'HIGH': 1.4\n };\n\n const intensityMultiplier = intensityMultipliers[activityClassification.intensity as keyof typeof intensityMultipliers] || 1.0;\n const adjustedEmission = baseCalculation.total * intensityMultiplier;\n\n // Apply real-time electricity factors\n const deviceAdjustedEmission = baseCalculation.device * (realTimeFactors.electricityFactor / 0.709);\n \n const finalEmission = baseCalculation.website + deviceAdjustedEmission + baseCalculation.network;\n\n return {\n carbonEmission: Math.round(finalEmission * 100) / 100,\n activityType: activityClassification.category,\n confidence: Math.min(\n baseCalculation.confidence,\n activityClassification.confidence,\n realTimeFactors.confidence\n ),\n breakdown: {\n deviceEnergy: Math.round(deviceAdjustedEmission * 100) / 100,\n networkTransfer: Math.round(baseCalculation.network * 100) / 100,\n serverProcessing: Math.round(baseCalculation.website * 100) / 100,\n aiProcessing: activityClassification.category === 'AI_INTERACTION' ? \n Math.round(finalEmission * 0.3 * 100) / 100 : undefined\n },\n insights: insights.insights,\n recommendations: insights.recommendations\n };\n }\n\n // Helper methods\n private calculateNetworkEmission(input: CarbonCalculationInput): number {\n // Estimate data transfer based on time on page and activity\n const estimatedDataMB = Math.min(input.timeOnPage * 0.1, 50); // Max 50MB\n \n const networkEmissionFactors = {\n 'wifi': 0.05,\n '4g': 0.18,\n '5g': 0.08,\n 'ethernet': 0.03\n };\n\n const factor = networkEmissionFactors[input.networkType as keyof typeof networkEmissionFactors] || 0.12;\n return estimatedDataMB * factor;\n }\n\n private fallbackClassification(domain: string): string {\n if (domain.includes('google') || domain.includes('bing')) return 'SEARCH';\n if (domain.includes('youtube') || domain.includes('netflix')) return 'STREAMING';\n if (domain.includes('facebook') || domain.includes('twitter')) return 'SOCIAL_MEDIA';\n if (domain.includes('amazon') || domain.includes('shop')) return 'SHOPPING';\n if (domain.includes('openai') || domain.includes('claude')) return 'AI_INTERACTION';\n return 'OTHER';\n }\n\n private extractElectricityFactor(data: any, country: string): number {\n // Extract electricity emission factor from Climatiq response\n // This is a simplified implementation\n const countryFactors: { [key: string]: number } = {\n 'US': 0.709,\n 'UK': 0.233,\n 'DE': 0.401,\n 'FR': 0.056,\n 'CA': 0.130,\n 'AU': 0.81\n };\n \n return countryFactors[country] || 0.709;\n }\n\n private getFallbackCalculation(input: CarbonCalculationInput): AIEnhancedResult {\n return {\n carbonEmission: 3.5,\n activityType: 'OTHER',\n confidence: 0.3,\n breakdown: {\n deviceEnergy: 1.5,\n networkTransfer: 1.0,\n serverProcessing: 1.0\n },\n insights: ['Basic calculation used due to AI service unavailability'],\n recommendations: ['Enable AI features for personalized recommendations']\n };\n }\n}\n\n// Enhanced API endpoint integration\nexport async function enhancedCarbonCalculation(\n url: string,\n timeOnPage: number,\n userContext: any\n) {\n const calculator = new AIEnhancedCarbonCalculator();\n \n const input: CarbonCalculationInput = {\n url,\n domain: new URL(url).hostname,\n pageTitle: userContext.pageTitle || '',\n timeOnPage,\n scrollDepth: userContext.scrollDepth || 0,\n clickCount: userContext.clickCount || 0,\n deviceType: userContext.deviceType || 'laptop',\n networkType: userContext.networkType || 'wifi',\n location: userContext.location || { lat: 37.7749, lng: -122.4194, country: 'US' },\n userAgent: userContext.userAgent || '',\n timestamp: new Date()\n };\n\n return await calculator.calculateEnhancedCarbon(input);\n} "}, "025cfdb6714a9dc1b81e1fb5827ba069f357ae5b": {"t": 1785754622.0206869, "n": 12877, "h": "4eae079fb8624e98", "c": "// AI-Enhanced Carbon Footprint Calculator\n// Integrates DeepSeek V3 via OpenRouter API for improved accuracy and intelligence\n\nimport OpenAI from 'openai';\n\ninterface CarbonCalculationInput {\n url: string;\n domain: string;\n pageTitle: string;\n timeOnPage: number;\n scrollDepth: number;\n clickCount: number;\n deviceType: string;\n networkType: string;\n location: {\n lat: number;\n lng: number;\n country: string;\n };\n userAgent: string;\n timestamp: Date;\n}\n\ninterface AIEnhancedResult {\n carbonEmission: number;\n activityType: string;\n confidence: number;\n breakdown: {\n deviceEnergy: number;\n networkTransfer: number;\n serverProcessing: number;\n aiProcessing?: number;\n };\n insights: string[];\n recommendations: string[];\n}\n\nexport class AIEnhancedCarbonCalculator {\n private openrouterClient: OpenAI;\n private climatiqApiKey: string;\n private websiteEnergyDb: any[];\n private deviceEnergyDb: any[];\n\n constructor() {\n this.openrouterClient = new OpenAI({\n apiKey: process.env.DEEPSEEK_API_KEY, // OpenRouter API key\n baseURL: 'https://openrouter.ai/api/v1',\n });\n this.climatiqApiKey = process.env.CLIMATIQ_API_KEY || '';\n this.loadDatabases();\n }\n\n private loadDatabases() {\n // Load our training datasets\n try {\n this.websiteEnergyDb = require('../../training-data/website-energy-database.json');\n this.deviceEnergyDb = require('../../training-data/device-energy-consumption.json');\n } catch (error) {\n console.warn('Training datasets not found, using fallback data');\n this.websiteEnergyDb = [];\n this.deviceEnergyDb = [];\n }\n }\n\n // Main AI-enhanced calculation method\n async calculateEnhancedCarbon(input: CarbonCalculationInput): Promise<AIEnhancedResult> {\n try {\n // Step 1: Basic calculation using our database\n const baseCalculation = this.calculateBaseCarbon(input);\n \n // Step 2: AI-enhanced activity classification\n const activityClassification = await this.classifyActivityWithAI(input);\n \n // Step 3: Real-time emission factors from Climatiq\n const realTimeFactors = await this.getRealTimeEmissionFactors(input.location.country);\n \n // Step 4: AI-generated insights and recommendations\n const insights = await this.generateAIInsights(input, baseCalculation);\n \n // Step 5: Combine all data for final result\n const enhancedResult = this.combineCalculations(\n baseCalculation,\n activityClassification,\n realTimeFactors,\n insights\n );\n\n return enhancedResult;\n } catch (error) {\n console.error('AI-enhanced calculation failed:', error);\n // Fallback to basic calculation\n return this.getFallbackCalculation(input);\n }\n }\n\n // Basic carbon calculation using our datasets\n private calculateBaseCarbon(input: CarbonCalculationInput) {\n // Find website in our database\n const websiteData = this.websiteEnergyDb.find(site => \n input.domain.includes(site.domain.replace('www.', ''))\n );\n\n // Find device energy consumption\n const deviceData = this.deviceEnergyDb.find(device => \n input.deviceType.toLowerCase().includes(device.category)\n );\n\n // Calculate base emissions\n const websiteEmission = websiteData ? websiteData.co2_per_visit_g : 3.5; // Default\n const deviceEmission = deviceData ? \n (deviceData.browsing_watts * input.timeOnPage / 3600 * 0.709) : 2.1; // Default\n \n const networkEmission = this.calculateNetworkEmission(input);\n \n return {\n total: websiteEmission + deviceEmission + networkEmission,\n website: websiteEmission,\n device: deviceEmission,\n network: networkEmission,\n confidence: websiteData && deviceData ? 0.8 : 0.6\n };\n }\n\n // AI-powered activity classification using DeepSeek V3 via OpenRouter\n private async classifyActivityWithAI(input: CarbonCalculationInput) {\n const prompt = `\n Analyze this web activity and classify it for carbon footprint calculation:\n \n URL: ${input.url}\n Domain: ${input.domain}\n Page Title: ${input.pageTitle}\n Time on Page: ${input.timeOnPage}s\n Scroll Depth: ${input.scrollDepth}%\n Clicks: ${input.clickCount}\n \n Classify this activity into one of these categories:\n 1. SEARCH - Web searches\n 2. SOCIAL_MEDIA - Social platforms, messaging\n 3. STREAMING - Video/audio streaming\n 4. SHOPPING - E-commerce, browsing products\n 5. AI_INTERACTION - ChatGPT, Claude, AI tools\n 6. WORK - Productivity, email, documents\n 7. NEWS - Reading news, articles\n 8. GAMING - Online games\n 9. OTHER - Anything else\n \n Also estimate the carbon intensity (LOW/MEDIUM/HIGH) based on:\n - Page complexity and resource usage\n - User interaction level\n - Likely backend processing requirements\n \n Respond with ONLY a JSON object (no markdown formatting): {\"category\": \"...\", \"intensity\": \"...\", \"reasoning\": \"...\"}\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 200,\n temperature: 0.3\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n category: result.category || 'OTHER',\n intensity: result.intensity || 'MEDIUM',\n reasoning: result.reasoning || '',\n confidence: 0.85\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) classification failed:', error);\n return {\n category: this.fallbackClassification(input.domain),\n intensity: 'MEDIUM',\n reasoning: 'Fallback classification',\n confidence: 0.5\n };\n }\n }\n\n // Get real-time emission factors from Climatiq API\n private async getRealTimeEmissionFactors(country: string) {\n if (!this.climatiqApiKey) {\n return { electricityFactor: 0.709, confidence: 0.3 }; // US average fallback\n }\n\n try {\n const response = await fetch('https://api.climatiq.io/data/v1/emission-factors', {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.climatiqApiKey}`,\n 'Content-Type': 'application/json'\n }\n });\n\n if (response.ok) {\n const data = await response.json();\n // Extract electricity emission factor for the country\n const electricityFactor = this.extractElectricityFactor(data, country);\n return { electricityFactor, confidence: 0.9 };\n }\n } catch (error) {\n console.error('Climatiq API failed:', error);\n }\n\n return { electricityFactor: 0.709, confidence: 0.3 };\n }\n\n // Generate AI insights and recommendations using DeepSeek V3\n private async generateAIInsights(input: CarbonCalculationInput, calculation: any) {\n const prompt = `\n Based on this web activity carbon calculation, provide insights and recommendations:\n \n Activity: ${input.domain} for ${input.timeOnPage}s\n Carbon Emission: ${calculation.total.toFixed(2)}g CO2\n Device: ${input.deviceType}\n \n Provide:\n 1. 2-3 brief insights about this activity's environmental impact\n 2. 2-3 actionable recommendations to reduce emissions\n \n Keep responses concise and practical. Focus on digital behavior changes.\n \n Respond with ONLY a JSON object (no markdown formatting): {\n \"insights\": [\"insight1\", \"insight2\"],\n \"recommendations\": [\"rec1\", \"rec2\"]\n }\n `;\n\n try {\n const response = await this.openrouterClient.chat.completions.create({\n model: \"deepseek/deepseek-chat-v3-0324\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 300,\n temperature: 0.7\n });\n\n let content = response.choices[0].message.content || '{}';\n \n // Remove markdown JSON formatting if present\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n \n const result = JSON.parse(content);\n return {\n insights: result.insights || [],\n recommendations: result.recommendations || []\n };\n } catch (error) {\n console.error('DeepSeek V3 (OpenRouter) insights generation failed:', error);\n return {\n insights: ['This activity contributed to your digital carbon footprint'],\n recommendations: ['Consider reducing time on high-emission websites']\n };\n }\n }\n\n // Combine all calculations and AI insights\n private combineCalculations(\n baseCalculation: any,\n activityClassification: any,\n realTimeFactors: any,\n insights: any\n ): AIEnhancedResult {\n // Adjust base calculation based on AI classification\n const intensityMultipliers = {\n 'LOW': 0.7,\n 'MEDIUM': 1.0,\n 'HIGH': 1.4\n };\n\n const intensityMultiplier = intensityMultipliers[activityClassification.intensity as keyof typeof intensityMultipliers] || 1.0;\n const adjustedEmission = baseCalculation.total * intensityMultiplier;\n\n // Apply real-time electricity factors\n const deviceAdjustedEmission = baseCalculation.device * (realTimeFactors.electricityFactor / 0.709);\n \n const finalEmission = baseCalculation.website + deviceAdjustedEmission + baseCalculation.network;\n\n return {\n carbonEmission: Math.round(finalEmission * 100) / 100,\n activityType: activityClassification.category,\n confidence: Math.min(\n baseCalculation.confidence,\n activityClassification.confidence,\n realTimeFactors.confidence\n ),\n breakdown: {\n deviceEnergy: Math.round(deviceAdjustedEmission * 100) / 100,\n networkTransfer: Math.round(baseCalculation.network * 100) / 100,\n serverProcessing: Math.round(baseCalculation.website * 100) / 100,\n aiProcessing: activityClassification.category === 'AI_INTERACTION' ? \n Math.round(finalEmission * 0.3 * 100) / 100 : undefined\n },\n insights: insights.insights,\n recommendations: insights.recommendations\n };\n }\n\n // Helper methods\n private calculateNetworkEmission(input: CarbonCalculationInput): number {\n // Estimate data transfer based on time on page and activity\n const estimatedDataMB = Math.min(input.timeOnPage * 0.1, 50); // Max 50MB\n \n const networkEmissionFactors = {\n 'wifi': 0.05,\n '4g': 0.18,\n '5g': 0.08,\n 'ethernet': 0.03\n };\n\n const factor = networkEmissionFactors[input.networkType as keyof typeof networkEmissionFactors] || 0.12;\n return estimatedDataMB * factor;\n }\n\n private fallbackClassification(domain: string): string {\n if (domain.includes('google') || domain.includes('bing')) return 'SEARCH';\n if (domain.includes('youtube') || domain.includes('netflix')) return 'STREAMING';\n if (domain.includes('facebook') || domain.includes('twitter')) return 'SOCIAL_MEDIA';\n if (domain.includes('amazon') || domain.includes('shop')) return 'SHOPPING';\n if (domain.includes('openai') || domain.includes('claude')) return 'AI_INTERACTION';\n return 'OTHER';\n }\n\n private extractElectricityFactor(data: any, country: string): number {\n // Extract electricity emission factor from Climatiq response\n // This is a simplified implementation\n const countryFactors: { [key: string]: number } = {\n 'US': 0.709,\n 'UK': 0.233,\n 'DE': 0.401,\n 'FR': 0.056,\n 'CA': 0.130,\n 'AU': 0.81\n };\n \n return countryFactors[country] || 0.709;\n }\n\n private getFallbackCalculation(input: CarbonCalculationInput): AIEnhancedResult {\n return {\n carbonEmission: 3.5,\n activityType: 'OTHER',\n confidence: 0.3,\n breakdown: {\n deviceEnergy: 1.5,\n networkTransfer: 1.0,\n serverProcessing: 1.0\n },\n insights: ['Basic calculation used due to AI service unavailability'],\n recommendations: ['Enable AI features for personalized recommendations']\n };\n }\n}\n\n// Enhanced API endpoint integration\nexport async function enhancedCarbonCalculation(\n url: string,\n timeOnPage: number,\n userContext: any\n) {\n const calculator = new AIEnhancedCarbonCalculator();\n \n const input: CarbonCalculationInput = {\n url,\n domain: new URL(url).hostname,\n pageTitle: userContext.pageTitle || '',\n timeOnPage,\n scrollDepth: userContext.scrollDepth || 0,\n clickCount: userContext.clickCount || 0,\n deviceType: userContext.deviceType || 'laptop',\n networkType: userContext.networkType || 'wifi',\n location: userContext.location || { lat: 37.7749, lng: -122.4194, country: 'US' },\n userAgent: userContext.userAgent || '',\n timestamp: new Date()\n };\n\n return await calculator.calculateEnhancedCarbon(input);\n} "}, "41a77c0b708fb9705168d0f57dfb1600a979e6ab": {"t": 1785754623.413536, "n": 12179, "h": "77b1ef3097380a23", "c": "// AI-Enhanced Carbon Footprint Calculator\n// Integrates multiple AI APIs for improved accuracy and intelligence\n\nimport OpenAI from 'openai';\n\ninterface CarbonCalculationInput {\n url: string;\n domain: string;\n pageTitle: string;\n timeOnPage: number;\n scrollDepth: number;\n clickCount: number;\n deviceType: string;\n networkType: string;\n location: {\n lat: number;\n lng: number;\n country: string;\n };\n userAgent: string;\n timestamp: Date;\n}\n\ninterface AIEnhancedResult {\n carbonEmission: number;\n activityType: string;\n confidence: number;\n breakdown: {\n deviceEnergy: number;\n networkTransfer: number;\n serverProcessing: number;\n aiProcessing?: number;\n };\n insights: string[];\n recommendations: string[];\n}\n\nexport class AIEnhancedCarbonCalculator {\n private openai: OpenAI;\n private climatiqApiKey: string;\n private websiteEnergyDb: any[];\n private deviceEnergyDb: any[];\n\n constructor() {\n this.openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n });\n this.climatiqApiKey = process.env.CLIMATIQ_API_KEY || '';\n this.loadDatabases();\n }\n\n private loadDatabases() {\n // Load our training datasets\n try {\n this.websiteEnergyDb = require('../../training-data/website-energy-database.json');\n this.deviceEnergyDb = require('../../training-data/device-energy-consumption.json');\n } catch (error) {\n console.warn('Training datasets not found, using fallback data');\n this.websiteEnergyDb = [];\n this.deviceEnergyDb = [];\n }\n }\n\n // Main AI-enhanced calculation method\n async calculateEnhancedCarbon(input: CarbonCalculationInput): Promise<AIEnhancedResult> {\n try {\n // Step 1: Basic calculation using our database\n const baseCalculation = this.calculateBaseCarbon(input);\n \n // Step 2: AI-enhanced activity classification\n const activityClassification = await this.classifyActivityWithAI(input);\n \n // Step 3: Real-time emission factors from Climatiq\n const realTimeFactors = await this.getRealTimeEmissionFactors(input.location.country);\n \n // Step 4: AI-generated insights and recommendations\n const insights = await this.generateAIInsights(input, baseCalculation);\n \n // Step 5: Combine all data for final result\n const enhancedResult = this.combineCalculations(\n baseCalculation,\n activityClassification,\n realTimeFactors,\n insights\n );\n\n return enhancedResult;\n } catch (error) {\n console.error('AI-enhanced calculation failed:', error);\n // Fallback to basic calculation\n return this.getFallbackCalculation(input);\n }\n }\n\n // Basic carbon calculation using our datasets\n private calculateBaseCarbon(input: CarbonCalculationInput) {\n // Find website in our database\n const websiteData = this.websiteEnergyDb.find(site => \n input.domain.includes(site.domain.replace('www.', ''))\n );\n\n // Find device energy consumption\n const deviceData = this.deviceEnergyDb.find(device => \n input.deviceType.toLowerCase().includes(device.category)\n );\n\n // Calculate base emissions\n const websiteEmission = websiteData ? websiteData.co2_per_visit_g : 3.5; // Default\n const deviceEmission = deviceData ? \n (deviceData.browsing_watts * input.timeOnPage / 3600 * 0.709) : 2.1; // Default\n \n const networkEmission = this.calculateNetworkEmission(input);\n \n return {\n total: websiteEmission + deviceEmission + networkEmission,\n website: websiteEmission,\n device: deviceEmission,\n network: networkEmission,\n confidence: websiteData && deviceData ? 0.8 : 0.6\n };\n }\n\n // AI-powered activity classification\n private async classifyActivityWithAI(input: CarbonCalculationInput) {\n const prompt = `\n Analyze this web activity and classify it for carbon footprint calculation:\n \n URL: ${input.url}\n Domain: ${input.domain}\n Page Title: ${input.pageTitle}\n Time on Page: ${input.timeOnPage}s\n Scroll Depth: ${input.scrollDepth}%\n Clicks: ${input.clickCount}\n \n Classify this activity into one of these categories:\n 1. SEARCH - Web searches\n 2. SOCIAL_MEDIA - Social platforms, messaging\n 3. STREAMING - Video/audio streaming\n 4. SHOPPING - E-commerce, browsing products\n 5. AI_INTERACTION - ChatGPT, Claude, AI tools\n 6. WORK - Productivity, email, documents\n 7. NEWS - Reading news, articles\n 8. GAMING - Online games\n 9. OTHER - Anything else\n \n Also estimate the carbon intensity (LOW/MEDIUM/HIGH) based on:\n - Page complexity and resource usage\n - User interaction level\n - Likely backend processing requirements\n \n Respond with JSON: {\"category\": \"...\", \"intensity\": \"...\", \"reasoning\": \"...\"}\n `;\n\n try {\n const response = await this.openai.chat.completions.create({\n model: \"o4-mini\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 200,\n temperature: 0.3\n });\n\n const result = JSON.parse(response.choices[0].message.content || '{}');\n return {\n category: result.category || 'OTHER',\n intensity: result.intensity || 'MEDIUM',\n reasoning: result.reasoning || '',\n confidence: 0.85\n };\n } catch (error) {\n console.error('AI classification failed:', error);\n return {\n category: this.fallbackClassification(input.domain),\n intensity: 'MEDIUM',\n reasoning: 'Fallback classification',\n confidence: 0.5\n };\n }\n }\n\n // Get real-time emission factors from Climatiq API\n private async getRealTimeEmissionFactors(country: string) {\n if (!this.climatiqApiKey) {\n return { electricityFactor: 0.709, confidence: 0.3 }; // US average fallback\n }\n\n try {\n const response = await fetch('https://api.climatiq.io/data/v1/emission-factors', {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.climatiqApiKey}`,\n 'Content-Type': 'application/json'\n }\n });\n\n if (response.ok) {\n const data = await response.json();\n // Extract electricity emission factor for the country\n const electricityFactor = this.extractElectricityFactor(data, country);\n return { electricityFactor, confidence: 0.9 };\n }\n } catch (error) {\n console.error('Climatiq API failed:', error);\n }\n\n return { electricityFactor: 0.709, confidence: 0.3 };\n }\n\n // Generate AI insights and recommendations\n private async generateAIInsights(input: CarbonCalculationInput, calculation: any) {\n const prompt = `\n Based on this web activity carbon calculation, provide insights and recommendations:\n \n Activity: ${input.domain} for ${input.timeOnPage}s\n Carbon Emission: ${calculation.total.toFixed(2)}g CO2\n Device: ${input.deviceType}\n \n Provide:\n 1. 2-3 brief insights about this activity's environmental impact\n 2. 2-3 actionable recommendations to reduce emissions\n \n Keep responses concise and practical. Focus on digital behavior changes.\n \n Respond with JSON: {\n \"insights\": [\"insight1\", \"insight2\"],\n \"recommendations\": [\"rec1\", \"rec2\"]\n }\n `;\n\n try {\n const response = await this.openai.chat.completions.create({\n model: \"o4-mini\",\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: 300,\n temperature: 0.7\n });\n\n const result = JSON.parse(response.choices[0].message.content || '{}');\n return {\n insights: result.insights || [],\n recommendations: result.recommendations || []\n };\n } catch (error) {\n console.error('AI insights generation failed:', error);\n return {\n insights: ['This activity contributed to your digital carbon footprint'],\n recommendations: ['Consider reducing time on high-emission websites']\n };\n }\n }\n\n // Combine all calculations and AI insights\n private combineCalculations(\n baseCalculation: any,\n activityClassification: any,\n realTimeFactors: any,\n insights: any\n ): AIEnhancedResult {\n // Adjust base calculation based on AI classification\n const intensityMultipliers = {\n 'LOW': 0.7,\n 'MEDIUM': 1.0,\n 'HIGH': 1.4\n };\n\n const intensityMultiplier = intensityMultipliers[activityClassification.intensity as keyof typeof intensityMultipliers] || 1.0;\n const adjustedEmission = baseCalculation.total * intensityMultiplier;\n\n // Apply real-time electricity factors\n const deviceAdjustedEmission = baseCalculation.device * (realTimeFactors.electricityFactor / 0.709);\n \n const finalEmission = baseCalculation.website + deviceAdjustedEmission + baseCalculation.network;\n\n return {\n carbonEmission: Math.round(finalEmission * 100) / 100,\n activityType: activityClassification.category,\n confidence: Math.min(\n baseCalculation.confidence,\n activityClassification.confidence,\n realTimeFactors.confidence\n ),\n breakdown: {\n deviceEnergy: Math.round(deviceAdjustedEmission * 100) / 100,\n networkTransfer: Math.round(baseCalculation.network * 100) / 100,\n serverProcessing: Math.round(baseCalculation.website * 100) / 100,\n aiProcessing: activityClassification.category === 'AI_INTERACTION' ? \n Math.round(finalEmission * 0.3 * 100) / 100 : undefined\n },\n insights: insights.insights,\n recommendations: insights.recommendations\n };\n }\n\n // Helper methods\n private calculateNetworkEmission(input: CarbonCalculationInput): number {\n // Estimate data transfer based on time on page and activity\n const estimatedDataMB = Math.min(input.timeOnPage * 0.1, 50); // Max 50MB\n \n const networkEmissionFactors = {\n 'wifi': 0.05,\n '4g': 0.18,\n '5g': 0.08,\n 'ethernet': 0.03\n };\n\n const factor = networkEmissionFactors[input.networkType as keyof typeof networkEmissionFactors] || 0.12;\n return estimatedDataMB * factor;\n }\n\n private fallbackClassification(domain: string): string {\n if (domain.includes('google') || domain.includes('bing')) return 'SEARCH';\n if (domain.includes('youtube') || domain.includes('netflix')) return 'STREAMING';\n if (domain.includes('facebook') || domain.includes('twitter')) return 'SOCIAL_MEDIA';\n if (domain.includes('amazon') || domain.includes('shop')) return 'SHOPPING';\n if (domain.includes('openai') || domain.includes('claude')) return 'AI_INTERACTION';\n return 'OTHER';\n }\n\n private extractElectricityFactor(data: any, country: string): number {\n // Extract electricity emission factor from Climatiq response\n // This is a simplified implementation\n const countryFactors: { [key: string]: number } = {\n 'US': 0.709,\n 'UK': 0.233,\n 'DE': 0.401,\n 'FR': 0.056,\n 'CA': 0.130,\n 'AU': 0.81\n };\n \n return countryFactors[country] || 0.709;\n }\n\n private getFallbackCalculation(input: CarbonCalculationInput): AIEnhancedResult {\n return {\n carbonEmission: 3.5,\n activityType: 'OTHER',\n confidence: 0.3,\n breakdown: {\n deviceEnergy: 1.5,\n networkTransfer: 1.0,\n serverProcessing: 1.0\n },\n insights: ['Basic calculation used due to AI service unavailability'],\n recommendations: ['Enable AI features for personalized recommendations']\n };\n }\n}\n\n// Enhanced API endpoint integration\nexport async function enhancedCarbonCalculation(\n url: string,\n timeOnPage: number,\n userContext: any\n) {\n const calculator = new AIEnhancedCarbonCalculator();\n \n const input: CarbonCalculationInput = {\n url,\n domain: new URL(url).hostname,\n pageTitle: userContext.pageTitle || '',\n timeOnPage,\n scrollDepth: userContext.scrollDepth || 0,\n clickCount: userContext.clickCount || 0,\n deviceType: userContext.deviceType || 'laptop',\n networkType: userContext.networkType || 'wifi',\n location: userContext.location || { lat: 37.7749, lng: -122.4194, country: 'US' },\n userAgent: userContext.userAgent || '',\n timestamp: new Date()\n };\n\n return await calculator.calculateEnhancedCarbon(input);\n} "}}}}