/**
 * Analytics CLI command — Metrics dashboards
 *
 * Usage:
 *   morph-spec analytics feature <name>
 *   morph-spec analytics context <name>
 *   morph-spec analytics project [--period=30d]
 */

import chalk from 'chalk';
import {
  getFeatureAnalytics, getProjectAnalytics,
  generateAsciiChart, generateTimelineChart,
  recordEvent
} from '../../lib/analytics/analytics-engine.js';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

// ============================================================================
// Feature Analytics Dashboard
// ============================================================================

export async function analyticsFeatureCommand(featureName, options) {
  try {
    const analytics = getFeatureAnalytics(featureName);

    console.log(chalk.cyan(`\n  Feature Analytics — ${featureName}\n`));
    console.log('  ' + '─'.repeat(50));

    console.log(`\n  Threads:`);
    for (const [status, count] of Object.entries(analytics.threads)) {
      console.log(`    ${status.padEnd(12)} ${count}`);
    }

    console.log(`\n  Performance:`);
    console.log(`    Checkpoint pass rate:  ${analytics.checkpointPassRate}%`);
    console.log(`    Total duration:        ${formatDuration(analytics.totalDuration)}`);
    console.log(`    Total tool calls:      ${analytics.totalToolCalls}`);
    console.log(`    Total tokens used:     ${analytics.totalTokensUsed.toLocaleString()}`);
    console.log(`    Context optimizations: ${analytics.optimizationEvents}`);

    if (Object.keys(analytics.threads).length > 0) {
      console.log('\n' + generateAsciiChart(analytics.threads, { title: 'Threads by Status' }));
    }

    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

// ============================================================================
// Context Analytics Dashboard
// ============================================================================

export async function analyticsContextCommand(featureName, options) {
  try {
    // Load context events from JSONL
    const contextLogPath = join(process.cwd(), '.morph/analytics/context-log.jsonl');

    if (!existsSync(contextLogPath)) {
      console.log(chalk.gray(`  No context analytics found for: ${featureName}`));
      console.log(chalk.gray('  Run a session with context tracking to populate analytics.\n'));
      return;
    }

    const lines = readFileSync(contextLogPath, 'utf8').trim().split('\n').filter(Boolean);
    const events = lines.map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
    const featureEvents = events.filter(e => e.feature === featureName);

    const tokenSamples = featureEvents.filter(e => e.type === 'token_usage');
    const criticalMoments = featureEvents.filter(e => e.type === 'context_critical');
    const optimizations = featureEvents.filter(e => e.type === 'context_optimized');

    console.log(chalk.cyan(`\n  Context Analytics — ${featureName}\n`));
    console.log('  ' + '─'.repeat(50));

    if (tokenSamples.length === 0) {
      console.log(chalk.gray('  No token usage data available.\n'));
      return;
    }

    const avgTokens = Math.round(tokenSamples.reduce((s, e) => s + (e.data?.tokensUsed || 0), 0) / tokenSamples.length);
    const peakTokens = Math.max(...tokenSamples.map(e => e.data?.tokensUsed || 0));
    const avgUtilization = Math.round(tokenSamples.reduce((s, e) => s + (e.data?.utilization || 0), 0) / tokenSamples.length * 100);

    console.log(`\n  Token Usage:`);
    console.log(`    Average tokens:      ${avgTokens.toLocaleString()}`);
    console.log(`    Peak tokens:         ${peakTokens.toLocaleString()}`);
    console.log(`    Avg utilization:     ${avgUtilization}%`);
    console.log(`    Critical moments:    ${criticalMoments.length}`);
    console.log(`    Optimizations applied: ${optimizations.length}`);

    // Optimization opportunities
    if (criticalMoments.length > 0) {
      console.log(chalk.yellow('\n  ⚠ Optimization Opportunities:'));
      const recs = criticalMoments.flatMap(e => e.data?.recommendations || []);
      const uniqueStrategies = [...new Set(recs.map(r => r.strategy))];
      for (const strategy of uniqueStrategies) {
        const rec = recs.find(r => r.strategy === strategy);
        console.log(`    • ${strategy}: ${rec?.description || ''}`);
        console.log(`      Savings: ${rec?.estimatedSavings || 'unknown'}`);
      }
    }

    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

// ============================================================================
// Project-Wide Dashboard
// ============================================================================

export async function analyticsProjectCommand(options) {
  try {
    const analytics = getProjectAnalytics();

    console.log(chalk.cyan(`\n  Project Analytics Dashboard — ${analytics.period}\n`));
    console.log('  ' + '═'.repeat(55));

    console.log(`\n  📊 Overview`);
    console.log(`    Features tracked:   ${analytics.features}`);
    console.log(`    Total threads:      ${analytics.threads.total}`);
    console.log(`      Completed:        ${analytics.threads.completed}`);
    console.log(`      Failed:           ${analytics.threads.failed}`);

    console.log(`\n  ✓ Checkpoints`);
    console.log(`    Total run:          ${analytics.checkpoints.total}`);
    console.log(`    Passed:             ${analytics.checkpoints.passed}`);
    console.log(`    Pass rate:          ${analytics.checkpoints.passRate}%`);

    if (analytics.checkpoints.total > 0) {
      const bar = buildBar(analytics.checkpoints.passRate, 30);
      console.log(`    ${bar}`);
    }

    console.log(`\n  ⫸ Parallelization`);
    console.log(`    Avg concurrency:    ${analytics.parallelization.avgConcurrency}x`);
    console.log(`    Parallel threads:   ${analytics.parallelization.parallelThreads}`);

    console.log(`\n  ⚡ Trust & Auto-Approval`);
    console.log(`    Auto-approvals:     ${analytics.trust.autoApprovals}`);
    console.log(`    Trust level changes: ${analytics.trust.trustChanges}`);

    console.log(`\n  🧠 Context`);
    console.log(`    Avg tokens/session: ${analytics.context.avgTokensPerSession.toLocaleString()}`);
    console.log(`    Optimizations:      ${analytics.context.optimizations}`);

    console.log('\n  ' + '─'.repeat(55));
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

// ============================================================================
// Helpers
// ============================================================================

function formatDuration(seconds) {
  if (!seconds) return '—';
  if (seconds < 60) return `${seconds}s`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
  return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}

function buildBar(pct, width) {
  const filled = Math.round(pct / 100 * width);
  const color = pct >= 90 ? chalk.green : pct >= 70 ? chalk.yellow : chalk.red;
  return color('[' + '█'.repeat(filled) + '░'.repeat(width - filled) + `] ${pct}%`);
}
