#!/usr/bin/env node
/**
 * ReePoe Admin CLI - Administrative tools
 */

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

const client = new ActivationClient();

async function promptInput(question) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    return new Promise((resolve) => {
        rl.question(question, (answer) => {
            rl.close();
            resolve(answer.trim());
        });
    });
}

async function adminLogin() {
    console.log('\n╔═══════════════════════════════════════════════════════════════╗');
    console.log('║  🔐 ReePoe Admin Login                                        ║');
    console.log('╚═══════════════════════════════════════════════════════════════╝\n');
    
    const email = await promptInput('📧 Admin Email: ');
    const adminCode = await promptInput('🔑 Admin Code: ');
    
    console.log('\n⏳ Authenticating...\n');
    
    try {
        const result = await client.adminLogin(email, adminCode);
        
        if (result.success) {
            console.log('✅ Admin access granted!');
            console.log(`   Token valid for: 1 hour`);
            console.log(`   Permissions: Full admin access\n`);
            console.log('Commands available:');
            console.log('   reepoe admin users list');
            console.log('   reepoe admin codes generate');
            console.log('   reepoe admin metrics\n');
        } else {
            console.log(`❌ Login failed: ${result.message || 'Invalid credentials'}\n`);
            process.exit(1);
        }
    } catch (error) {
        console.error(`❌ Login error: ${error.message}\n`);
        process.exit(1);
    }
}

async function listUsers(options = {}) {
    try {
        const result = await client.adminListUsers(options.status, options.limit || 50);
        
        console.log('\n╔═══════════════════════════════════════════════════════════════╗');
        console.log(`║  👥 Users (${result.total} total)${' '.repeat(47 - result.total.toString().length)}║`);
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        
        if (result.users.length === 0) {
            console.log('No users found.\n');
            return;
        }
        
        // Table header
        console.log('Email                      Status    Queries  Tokens Saved  Expires');
        console.log('─────────────────────────────────────────────────────────────────');
        
        for (const user of result.users) {
            const email = user.email.substring(0, 25).padEnd(26);
            const status = user.status.padEnd(9);
            const queries = String(user.total_queries || 0).padStart(7);
            const tokens = String(user.total_tokens_saved || 0).padStart(13);
            
            let expires = '    -   ';
            if (user.expires_at) {
                const expDate = new Date(user.expires_at);
                const days = Math.ceil((expDate - new Date()) / (1000 * 60 * 60 * 24));
                expires = `${days}d`.padStart(8);
            }
            
            console.log(`${email}${status}${queries} ${tokens}${expires}`);
        }
        
        console.log('\n💡 Commands:');
        console.log('   reepoe admin users extend <email> +30d');
        console.log('   reepoe admin users revoke <email>\n');
        
    } catch (error) {
        console.error(`\n❌ Failed to list users: ${error.message}\n`);
        process.exit(1);
    }
}

async function generateCodes(count, options = {}) {
    try {
        const codeType = options.type || 'ALPHA';
        const notes = options.notes;
        const adminEmail = 'admin';  // TODO: Get from admin session
        
        console.log('\n╔═══════════════════════════════════════════════════════════════╗');
        console.log('║  🔑 Generating Activation Codes                               ║');
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        
        console.log(`Type: ${codeType}`);
        console.log(`Count: ${count}`);
        console.log(`Expires: 30 days from now\n`);
        
        console.log('⏳ Generating...\n');
        
        const result = await client.adminGenerateCodes(count, codeType, adminEmail, notes);
        
        if (result.success) {
            console.log(`✅ Generated ${result.count} codes!\n`);
            
            console.log('Codes:');
            result.codes.forEach((code, i) => {
                console.log(`   ${i + 1}. ${code}`);
            });
            
            // Save to file
            const filename = `alpha_codes_${Date.now()}.txt`;
            fs.writeFileSync(filename, result.codes.join('\n'));
            
            console.log(`\n📄 Saved to: ${filename}`);
            console.log(`\n💡 Share these codes with alpha testers!\n`);
        } else {
            console.log(`❌ Failed to generate codes\n`);
        }
        
    } catch (error) {
        console.error(`\n❌ Code generation failed: ${error.message}\n`);
        process.exit(1);
    }
}

async function extendUser(email, days) {
    try {
        const adminEmail = 'admin';  // TODO: Get from admin session
        
        console.log(`\n⏳ Extending ${email} by ${days} days...\n`);
        
        const result = await client.adminExtendUser(email, days, adminEmail);
        
        if (result.success) {
            console.log(`✅ ${result.message}`);
            console.log(`   New expiration: ${new Date(result.new_expires_at).toLocaleDateString()}\n`);
        } else {
            console.log(`❌ Extension failed: ${result.error}\n`);
        }
        
    } catch (error) {
        console.error(`\n❌ Extension error: ${error.message}\n`);
        process.exit(1);
    }
}

// Parse command line arguments
const args = process.argv.slice(2);
const command = args[0];
const subcommand = args[1];

async function showUserMetrics(email) {
    const axios = require('axios');
    
    try {
        console.log(`\n📊 Loading metrics for ${email}...\n`);
        
        // Get aggregate metrics (same as dashboard)
        const API_URL = process.env.REEPOE_API_URL || 'https://reepoe-api.onrender.com';
        const res = await axios.get(`${API_URL}/metrics`);
        const data = res.data;
        
        console.log('╔═══════════════════════════════════════════════════════════════╗');
        console.log(`║  📊 User Metrics - ${email.substring(0, 42).padEnd(42)}║`);
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        
        console.log('ALL TIME (Aggregate):');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Total Queries:     ${data.lifetime?.total_queries || 0}`);
        console.log(`   Tokens Saved:      ${(data.lifetime?.tokens_saved || 0).toLocaleString()}`);
        console.log(`   MiniRAG Hits:      ${data.lifetime?.mini_rag_hits || 0}`);
        console.log(`   Cache Hit Rate:    ${((data.performance?.cache_hit_rate || 0) * 100).toFixed(1)}%`);
        console.log('\n💡 Note: Showing aggregate metrics (per-user tracking in Phase 3C)\n');
        
    } catch (error) {
        console.error(`\n❌ Failed to load metrics: ${error.message}\n`);
        process.exit(1);
    }
}

async function showAggregateMetrics() {
    const axios = require('axios');
    
    try {
        console.log('\n📊 Loading aggregate metrics...\n');
        
        // Get users and metrics
        const users = await client.adminListUsers();
        const API_URL = process.env.REEPOE_API_URL || 'https://reepoe-api.onrender.com';
        const res = await axios.get(`${API_URL}/metrics`);
        const data = res.data;
        
        console.log('╔═══════════════════════════════════════════════════════════════╗');
        console.log('║  📊 ReePoe Admin Dashboard - Aggregate Metrics                ║');
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        
        console.log('USERS');
        console.log('─────────────────────────────────────────────────────');
        const activeUsers = users.users.filter(u => u.status === 'active').length;
        const waitlistUsers = users.users.filter(u => u.status === 'waitlist').length;
        console.log(`   Total:             ${users.total || 0}`);
        console.log(`   Active:            ${activeUsers}`);
        console.log(`   Waitlist:          ${waitlistUsers}`);
        
        console.log('\nUSAGE (ALL USERS)');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Total Queries:     ${data.lifetime?.total_queries || 0}`);
        console.log(`   Tokens Saved:      ${(data.lifetime?.tokens_saved || 0).toLocaleString()}`);
        console.log(`   MiniRAG Hits:      ${data.lifetime?.mini_rag_hits || 0}`);
        console.log(`   Cache Hit Rate:    ${((data.performance?.cache_hit_rate || 0) * 100).toFixed(1)}%`);
        
        console.log('\nPERFORMANCE');
        console.log('─────────────────────────────────────────────────────');
        console.log(`   Token Savings Rate: ${((data.performance?.token_savings_rate || 0) * 100).toFixed(1)}%`);
        console.log(`   Avg Response Time:  ${(data.performance?.avg_response_time_ms || 0).toFixed(0)}ms`);
        
        console.log('\n🌐 Dashboard: https://reepoe.com\n');
        
    } catch (error) {
        console.error(`\n❌ Failed to load metrics: ${error.message}\n`);
        process.exit(1);
    }
}

async function main() {
    if (command === 'login') {
        await adminLogin();
    } else if (command === 'users') {
        if (subcommand === 'list') {
            await listUsers({ status: args[2] });
        } else if (subcommand === 'extend' && args[2]) {
            const email = args[2];
            const days = parseInt(args[3]) || 30;
            await extendUser(email, days);
        } else if (subcommand === 'metrics' && args[2]) {
            const email = args[2];
            await showUserMetrics(email);
        } else {
            console.log('\nUsage:');
            console.log('   reepoe admin users list [status]');
            console.log('   reepoe admin users extend <email> <days>');
            console.log('   reepoe admin users metrics <email>\n');
        }
    } else if (command === 'codes') {
        if (subcommand === 'generate' && args[2]) {
            const count = parseInt(args[2]);
            await generateCodes(count);
        } else {
            console.log('\nUsage:');
            console.log('   reepoe admin codes generate <count>\n');
        }
    } else if (command === 'metrics') {
        await showAggregateMetrics();
    } else {
        console.log('\n╔═══════════════════════════════════════════════════════════════╗');
        console.log('║  🔐 ReePoe Admin CLI                                          ║');
        console.log('╚═══════════════════════════════════════════════════════════════╝\n');
        console.log('Commands:');
        console.log('   reepoe admin login');
        console.log('   reepoe admin users list');
        console.log('   reepoe admin users extend <email> <days>');
        console.log('   reepoe admin codes generate <count>\n');
    }
}

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

