#!/usr/bin/env node
/**
 * ReePoe Metrics - Display user's personal statistics
 */

const ActivationClient = require('../lib/activation-client');
const fs = require('fs');
const path = require('path');
const os = require('os');

async function showMetrics() {
    const axios = require('axios');
    const client = new ActivationClient();
    
    // Load activation to get email
    const activation = client.loadActivation();
    
    if (!activation) {
        console.log('\n❌ No activation found');
        console.log('   Please activate ReePoe first: reepoe-start\n');
        process.exit(1);
    }
    
    console.log('\n📊 Loading your ReePoe metrics...\n');
    
    try {
        let metricsData = null;
        
        // FIX #7: Check for local server first to get real-time local metrics
        try {
            // Try default port 8000 or check config
            let port = 8000;
            const configPath = path.join(process.cwd(), 'reepoe.config.json');
            if (fs.existsSync(configPath)) {
                const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
                port = config.api?.port || 8000;
            }
            
            const localRes = await axios.get(`http://localhost:${port}/metrics`, { timeout: 1000 });
            const localRaw = localRes.data;
            
            // Get today's date in YYYY-MM-DD format (LOCAL time, not UTC!)
            const getLocalDateString = (d) => {
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            
            const today = getLocalDateString(new Date());
            const todayData = localRaw.daily?.[today] || {};
            
            // Calculate THIS WEEK metrics by aggregating last 7 days
            const weekMetrics = { queries: 0, tokens_saved: 0, cost_saved: 0 };
            const dailyData = localRaw.daily || {};
            
            for (let i = 0; i < 7; i++) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                const dateKey = getLocalDateString(date);
                
                if (dailyData[dateKey]) {
                    weekMetrics.queries += dailyData[dateKey].total_queries || 0;
                    weekMetrics.tokens_saved += dailyData[dateKey].tokens_saved || 0;
                    // Cost saved calculation based on tokens (approx $0.003 per 1k tokens)
                    weekMetrics.cost_saved += ((dailyData[dateKey].tokens_saved || 0) / 1000) * 0.003;
                }
            }
            
            // Calculate cost saved for today
            const todayCostSaved = ((todayData.tokens_saved || 0) / 1000) * 0.003;
            
            // Transform raw local metrics to view structure
            metricsData = {
                metrics: {
                    today: {
                        queries: todayData.total_queries || 0,
                        tokens_saved: todayData.tokens_saved || 0,
                        cost_saved: todayCostSaved
                    },
                    week: weekMetrics,
                    alltime: {
                        queries: localRaw.lifetime?.total_queries || 0,
                        tokens_saved: localRaw.lifetime?.tokens_saved || 0,
                        cost_saved: ((localRaw.lifetime?.tokens_saved || 0) / 1000) * 0.003,
                        patterns_learned: Object.keys(localRaw.query_types || {}).length,
                        patterns_active: Object.keys(localRaw.query_types || {}).length
                    }
                },
                account: {
                    status: 'Active (Local)',
                    expires_at: null
                }
            };
            console.log('✅ Loaded from local server (real-time)');
        } catch (e) {
            // Local failed, fall back to remote API
        }
        
        if (!metricsData) {
            // Use per-user metrics endpoint with api_base from activation
            const API_BASE = activation.api_base || 'https://reepoe-api.onrender.com';
            const res = await axios.get(`${API_BASE}/api/metrics/user/${activation.email}`);
            const data = res.data;
            
            // Per-user endpoint returns the correct structure already
            metricsData = {
                metrics: data.metrics,  // Already has today, week, alltime
                account: data.account   // Already has activated_at, expires_at, status
            };
        }
        
        const metrics = metricsData;
        
        console.log('╔═══════════════════════════════════════════════════════════════╗');
        console.log(`║  📊 ReePoe Metrics - ${activation.email.padEnd(39)}║`);
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        
        console.log('TODAY');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Queries:           ${metrics.metrics.today.queries || 0}`);
        console.log(`   Tokens Saved:      ${(metrics.metrics.today.tokens_saved || 0).toLocaleString()}`);
        console.log(`   Cost Saved:        $${(metrics.metrics.today.cost_saved || 0).toFixed(2)}`);
        
        console.log('\nTHIS WEEK');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Queries:           ${metrics.metrics.week.queries || 0}`);
        console.log(`   Tokens Saved:      ${(metrics.metrics.week.tokens_saved || 0).toLocaleString()}`);
        console.log(`   Cost Saved:        $${(metrics.metrics.week.cost_saved || 0).toFixed(2)}`);
        
        console.log('\nALL TIME');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Queries:           ${metrics.metrics.alltime.queries || 0}`);
        console.log(`   Tokens Saved:      ${(metrics.metrics.alltime.tokens_saved || 0).toLocaleString()}`);
        console.log(`   Cost Saved:        $${(metrics.metrics.alltime.cost_saved || 0).toFixed(2)}`);
        console.log(`   Patterns Learned:  ${metrics.metrics.alltime.patterns_learned || 0}`);
        console.log(`   Patterns Active:   ${metrics.metrics.alltime.patterns_active || 0}`);
        
        console.log('\nACCOUNT INFO');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Status:            ✅ ${metrics.account.status}`);
        
        if (metrics.account.expires_at) {
            const expiresDate = new Date(metrics.account.expires_at);
            const daysRemaining = Math.ceil((expiresDate - new Date()) / (1000 * 60 * 60 * 24));
            console.log(`   Expires:           ${expiresDate.toLocaleDateString()}`);
            console.log(`   Days Remaining:    ${daysRemaining}`);
        }
        
        console.log('\n💡 Your Impact:');
        console.log(`   You've saved ${metrics.metrics.alltime.tokens_saved.toLocaleString()} tokens!`);
        if (metrics.metrics.alltime.patterns_active > 0) {
            console.log(`   ${metrics.metrics.alltime.patterns_active} query types are now instant (0 tokens)\n`);
        }
        
    } catch (error) {
        console.error(`\n❌ Failed to load metrics: ${error.message}\n`);
        process.exit(1);
    }
}

showMetrics().catch(error => {
    console.error(`❌ Error: ${error.message}`);
    process.exit(1);
});

