#!/usr/bin/env node
const { spawn } = require('child_process');
async function answerQ13CloudWatch() {
console.log('📊 Q13: WHAT IS THE LAST 30 DAYS (PER DAY) AMORTIZED COST FOR CLOUDWATCH SERVICE?');
console.log('=' .repeat(80));
// Calculate last 30 days
const endDate = '2025-08-27';
const startDate = '2025-07-28'; // 30 days back
console.log(`📅 Period: ${startDate} to ${endDate} (30 days)`);
console.log('☁️ Cloud: AWS');
console.log('🔧 Service: CloudWatch (AmazonCloudWatch)');
console.log('💰 Cost Type: Amortized');
console.log('📈 Granularity: Daily');
console.log('');
const server = spawn('node', ['dist/index.js'], {
stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
UMBRELLA_API_BASE_URL: 'https://api-front.umbrellacost.io/api/v1'
}
});
const responses = [];
server.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(line => line.trim());
for (const line of lines) {
try {
const response = JSON.parse(line);
responses.push(response);
} catch (e) {}
}
});
server.stderr.on('data', () => {}); // Suppress server logs
await new Promise(resolve => setTimeout(resolve, 2000));
// Authenticate
server.stdin.write(JSON.stringify({
jsonrpc: "2.0", id: 1, method: "tools/call",
params: {
name: 'authenticate_user',
arguments: { username: 'david+saola@umbrellacost.com', password: 'Dsamsung1!' }
}
}) + '\n');
console.log('🔐 Authenticating...\n');
await new Promise(resolve => setTimeout(resolve, 5000));
// Q13: CloudWatch daily costs for last 30 days with intelligent service matching
console.log('📡 Making API call for Q13...');
console.log('Parameters:');
console.log(` • Start Date: ${startDate}`);
console.log(` • End Date: ${endDate}`);
console.log(' • Group By: none');
console.log(' • Period: day');
console.log(' • Cost Type: cost (amortized)');
console.log(' • Cloud Context: aws');
console.log(' • Service Filter: CloudWatch (intelligent matching)');
console.log(' • Account ID: 932213950603');
console.log('');
server.stdin.write(JSON.stringify({
jsonrpc: "2.0", id: 2, method: "tools/call",
params: {
name: 'api___invoices_caui',
arguments: {
startDate: startDate,
endDate: endDate,
groupBy: 'none',
periodGranLevel: 'day',
costType: ['cost'],
isAmortized: true,
cloud_context: 'aws',
accountId: '932213950603',
service: 'CloudWatch',
_originalServiceFilter: 'CloudWatch' // For intelligent matching
}
}
}) + '\n');
console.log('⏳ Waiting for response...\n');
await new Promise(resolve => setTimeout(resolve, 15000));
const response = responses.find(r => r.id === 2);
if (!response) {
console.log('❌ NO RESPONSE RECEIVED');
server.kill();
return;
}
if (response.error) {
console.log('❌ ERROR:', response.error.message || 'Unknown error');
server.kill();
return;
}
if (response.result?.content?.[0]?.text) {
const text = response.result.content[0].text;
console.log('📄 COMPLETE API RESPONSE:');
console.log('=' .repeat(80));
console.log(text);
console.log('=' .repeat(80));
// Parse JSON if present
const jsonMatch = text.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch) {
try {
const data = JSON.parse(jsonMatch[1]);
console.log('\n📊 CLOUDWATCH COST ANALYSIS:');
console.log('=' .repeat(60));
if (Array.isArray(data)) {
console.log(`• Data Type: Array with ${data.length} daily records`);
// Calculate total and stats
let totalCost = 0;
let daysWithData = 0;
let maxDailyCost = 0;
let minDailyCost = Number.MAX_VALUE;
let maxDay = '';
let minDay = '';
data.forEach(item => {
const cost = parseFloat(item.total_cost || item.cost || 0);
const date = item.usage_date || item.date || '';
if (cost > 0) {
totalCost += cost;
daysWithData++;
if (cost > maxDailyCost) {
maxDailyCost = cost;
maxDay = date;
}
if (cost < minDailyCost && cost > 0) {
minDailyCost = cost;
minDay = date;
}
}
});
console.log(`💰 TOTAL CLOUDWATCH COST (30 days): $${totalCost.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})}`);
console.log(`📊 STATISTICS:`);
console.log(` • Days with data: ${daysWithData}/30`);
console.log(` • Average daily cost: $${(totalCost / Math.max(daysWithData, 1)).toFixed(2)}`);
console.log(` • Highest daily cost: $${maxDailyCost.toFixed(2)} (${maxDay})`);
console.log(` • Lowest daily cost: $${minDailyCost === Number.MAX_VALUE ? '0.00' : minDailyCost.toFixed(2)} (${minDay})`);
console.log('\n📅 DAILY CLOUDWATCH COST BREAKDOWN:');
console.log('-'.repeat(50));
// Sort by date and display all days
data
.sort((a, b) => (a.usage_date || '').localeCompare(b.usage_date || ''))
.forEach(item => {
const date = item.usage_date || item.date || 'Unknown';
const cost = parseFloat(item.total_cost || item.cost || 0);
const dayName = new Date(date).toLocaleDateString('en-US', { weekday: 'short' });
console.log(`📅 ${date} (${dayName}): $${cost.toFixed(2)}`);
});
// Weekly aggregation
console.log('\n📊 WEEKLY AGGREGATION:');
console.log('-'.repeat(40));
const weeklyTotals = {};
data.forEach(item => {
const date = new Date(item.usage_date || item.date);
const weekStart = new Date(date);
weekStart.setDate(date.getDate() - date.getDay()); // Start of week (Sunday)
const weekKey = weekStart.toISOString().split('T')[0];
if (!weeklyTotals[weekKey]) {
weeklyTotals[weekKey] = 0;
}
weeklyTotals[weekKey] += parseFloat(item.total_cost || item.cost || 0);
});
Object.entries(weeklyTotals)
.sort(([a], [b]) => a.localeCompare(b))
.forEach(([weekStart, cost]) => {
const weekEndDate = new Date(weekStart);
weekEndDate.setDate(weekEndDate.getDate() + 6);
console.log(`📅 Week of ${weekStart}: $${cost.toFixed(2)}`);
});
// Cost trend analysis
console.log('\n📈 COST TREND ANALYSIS:');
console.log('-'.repeat(40));
// Calculate daily changes
const sortedData = data
.filter(item => parseFloat(item.total_cost || item.cost || 0) > 0)
.sort((a, b) => (a.usage_date || '').localeCompare(b.usage_date || ''));
if (sortedData.length >= 2) {
const firstWeekAvg = sortedData.slice(0, 7).reduce((sum, item) =>
sum + parseFloat(item.total_cost || item.cost || 0), 0) / 7;
const lastWeekAvg = sortedData.slice(-7).reduce((sum, item) =>
sum + parseFloat(item.total_cost || item.cost || 0), 0) / 7;
const trend = ((lastWeekAvg - firstWeekAvg) / firstWeekAvg * 100);
console.log(` • First week average: $${firstWeekAvg.toFixed(2)}`);
console.log(` • Last week average: $${lastWeekAvg.toFixed(2)}`);
console.log(` • Trend: ${trend > 0 ? '↗️' : '↘️'} ${Math.abs(trend).toFixed(1)}% ${trend > 0 ? 'increase' : 'decrease'}`);
}
console.log('\n✅ Q13 ANSWER COMPLETE - CloudWatch daily costs analyzed');
} else {
console.log('• Data Type: Object');
console.log('• Keys:', Object.keys(data).join(', '));
}
} catch (e) {
console.log('❌ JSON parsing error:', e.message);
}
} else {
console.log('\n⚠️ No JSON data found in response');
// Try to extract cost information from text
const costMatches = text.match(/\$[\d,\.]+/g);
if (costMatches) {
console.log('💰 Cost values found in text:', costMatches.join(', '));
}
}
} else {
console.log('❌ INVALID RESPONSE FORMAT');
}
server.kill();
}
answerQ13CloudWatch().catch(console.error);