#!/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 {
        // 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
        const metrics = {
            metrics: data.metrics,  // Already has today, week, alltime
            account: data.account   // Already has activated_at, expires_at, status
        };
        
        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);
});

