/**
 * Core Four Tracker — Context/Model/Prompt/Tools tracking
 *
 * Tracks the "Core Four" metrics that determine LLM behavior:
 *   Context  — Token count breakdown by source
 *   Model    — Model name and context window
 *   Prompt   — Current request summary
 *   Tools    — Tool usage counts (Read/Write/Edit/Bash/etc.)
 *
 * Reads from analytics-engine for historical data.
 * Formats output for ASCII terminal display.
 */

import { readFileSync, existsSync } from 'fs';
import { join } from 'path';
import { recordContextEvent } from '../analytics/analytics-engine.js';

// In-memory state for current session
let currentSession = {
  model: null,
  contextWindow: 200000,
  contextBreakdown: {},
  promptSummary: '',
  toolCalls: {}
};

// ============================================================================
// Session Initialization
// ============================================================================

/**
 * Initialize Core Four tracking for a session
 * @param {Object} opts
 * @param {string} opts.model - Model name
 * @param {number} [opts.contextWindow] - Context window size
 * @param {string} [opts.feature] - Feature being worked on
 */
export function initCoreFour({ model, contextWindow = 200000, feature = '' }) {
  currentSession = {
    model,
    contextWindow,
    feature,
    contextBreakdown: {
      'CLAUDE.md': 0,
      standards: 0,
      templates: 0,
      spec: 0,
      conversation: 0,
      other: 0
    },
    promptSummary: '',
    toolCalls: {
      Read: 0,
      Write: 0,
      Edit: 0,
      Bash: 0,
      Glob: 0,
      Grep: 0,
      Task: 0,
      other: 0
    },
    startedAt: new Date().toISOString()
  };
}

// ============================================================================
// Tracking Updates
// ============================================================================

/**
 * Update context breakdown by source
 * @param {Object} breakdown - { sourceName: tokenCount }
 */
export function updateContextBreakdown(breakdown) {
  for (const [source, tokens] of Object.entries(breakdown)) {
    currentSession.contextBreakdown[source] = tokens;
  }
}

/**
 * Update current prompt summary
 * @param {string} summary - Brief summary of current request
 */
export function updatePromptSummary(summary) {
  currentSession.promptSummary = summary;
}

/**
 * Record a tool call
 * @param {string} toolName - Tool name (Read|Write|Edit|Bash|etc.)
 */
export function recordToolCall(toolName) {
  const key = currentSession.toolCalls.hasOwnProperty(toolName) ? toolName : 'other';
  currentSession.toolCalls[key] = (currentSession.toolCalls[key] || 0) + 1;

  if (currentSession.feature) {
    recordContextEvent({
      type: 'tool_call',
      feature: currentSession.feature,
      data: { tool: toolName }
    });
  }
}

// ============================================================================
// Display Formatting
// ============================================================================

/**
 * Get the current Core Four state
 * @returns {Object} Core Four metrics
 */
export function getCoreFour() {
  const totalContextTokens = Object.values(currentSession.contextBreakdown)
    .reduce((sum, v) => sum + v, 0);

  const contextUtilization = currentSession.contextWindow > 0
    ? Math.round(totalContextTokens / currentSession.contextWindow * 100)
    : 0;

  return {
    context: {
      total: totalContextTokens,
      window: currentSession.contextWindow,
      utilization: contextUtilization,
      breakdown: currentSession.contextBreakdown
    },
    model: {
      name: currentSession.model || 'unknown',
      contextWindow: currentSession.contextWindow,
      provider: 'Anthropic'
    },
    prompt: {
      summary: currentSession.promptSummary || '(no active prompt)',
      length: currentSession.promptSummary?.length || 0
    },
    tools: {
      calls: { ...currentSession.toolCalls },
      total: Object.values(currentSession.toolCalls).reduce((sum, v) => sum + v, 0)
    }
  };
}

/**
 * Format Core Four as ASCII display string
 * @returns {string} ASCII formatted Core Four display
 */
export function formatCoreFour() {
  const { context, model, prompt, tools } = getCoreFour();
  const lines = [];

  lines.push('╔══════════════════════════════════════════╗');
  lines.push('║          CORE FOUR DASHBOARD             ║');
  lines.push('╠══════════════════════════════════════════╣');

  // Context
  lines.push('║ CONTEXT                                  ║');
  const bar = buildProgressBar(context.utilization, 30);
  lines.push(`║  ${bar} ${String(context.utilization).padStart(3)}%          ║`);
  lines.push(`║  Total: ${String(context.total.toLocaleString()).padEnd(10)} Window: ${String(context.window.toLocaleString()).padEnd(8)}║`);

  // Breakdown
  for (const [src, tokens] of Object.entries(context.breakdown)) {
    if (tokens > 0) {
      const pct = Math.round(tokens / Math.max(context.total, 1) * 100);
      lines.push(`║    ${src.padEnd(14)} ${String(tokens.toLocaleString()).padStart(8)} (${String(pct).padStart(2)}%)     ║`);
    }
  }
  lines.push('║                                          ║');

  // Model
  lines.push('║ MODEL                                    ║');
  lines.push(`║  ${model.name.padEnd(40)}║`);
  lines.push(`║  Window: ${String(model.contextWindow.toLocaleString()).padEnd(32)}║`);
  lines.push('║                                          ║');

  // Prompt
  lines.push('║ PROMPT                                   ║');
  const pStr = (prompt.summary || '—').substring(0, 38);
  lines.push(`║  ${pStr.padEnd(40)}║`);
  lines.push('║                                          ║');

  // Tools
  lines.push('║ TOOLS                                    ║');
  lines.push(`║  Total calls: ${String(tools.total).padEnd(27)}║`);
  for (const [tool, count] of Object.entries(tools.calls)) {
    if (count > 0) {
      lines.push(`║    ${tool.padEnd(10)} ${String(count).padStart(4)} calls${' '.repeat(20)}║`);
    }
  }
  lines.push('╚══════════════════════════════════════════╝');

  return lines.join('\n');
}

function buildProgressBar(pct, width) {
  const filled = Math.round(pct / 100 * width);
  const empty = width - filled;
  const color = pct >= 90 ? '█' : pct >= 75 ? '▓' : '░';
  return '[' + color.repeat(filled) + '░'.repeat(empty) + ']';
}
