import { logger } from './logger.js';

/**
 * RTK (Rust Token Killer) Integration
 * Minimizes LLM token consumption by filtering and compressing command outputs
 */
export class RTKIntegration {
  constructor() {
    this.rtkPath = process.env.RTK_PATH || 'rtk';
    this.enabled = false;
    this.version = null;
  }

  async init() {
    try {
      // Check if RTK is installed
      const { execa } = await import('execa');
      const result = await execa(this.rtkPath, ['--version']);
      this.version = result.stdout.trim();
      this.enabled = true;
      logger.info(`✓ RTK integration initialized (v${this.version})`);
      return true;
    } catch (error) {
      logger.warn(`⚠ RTK not found at ${this.rtkPath}`);
      logger.warn(`  Install with: curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh`);
      this.enabled = false;
      return false;
    }
  }

  /**
   * Check if a command is supported by RTK
   */
  isCommandSupported(cmd) {
    const supportedCommands = [
      // Git commands
      'git', 'gh', 'gt',
      // Cargo commands
      'cargo',
      // Node/NPM commands
      'npm', 'pnpm', 'npx',
      // Python commands
      'ruff', 'pytest', 'pip', 'mypy',
      // Docker commands
      'docker', 'kubectl', 'aws',
      // Go commands
      'go', 'golangci-lint',
      // Ruby commands
      'rspec', 'rubocop', 'rake',
      // Dotnet commands
      'dotnet',
      // Testing frameworks
      'playwright', 'vitest', 'jest',
    ];

    return supportedCommands.some(supported => cmd.startsWith(supported));
  }

  /**
   * Optimize a command with RTK
   * @param {string} command - The command to optimize
   * @param {string[]} args - Command arguments
   * @returns {Promise<{success: boolean, stdout?: string, stderr?: string, savings?: number}>}
   */
  async optimizeCommand(command, args = []) {
    if (!this.enabled) {
      return { success: false, savings: 0 };
    }

    if (!this.isCommandSupported(command)) {
      return { success: false, savings: 0 };
    }

    try {
      const { execa } = await import('execa');
      const cmdString = `${command} ${args.join(' ')}`;

      logger.info(`🚀 Executing with RTK: ${cmdString.substring(0, 100)}...`);

      const result = await execa(this.rtkPath, [command, ...args], {
        timeout: 300000,
        cwd: process.cwd(),
      });

      const savings = this.parseSavings(result.stdout);

      logger.info(`✓ RTK optimized: ${savings > 0 ? `-${savings}% savings` : 'no savings'}`);

      return {
        success: true,
        stdout: result.stdout.trim(),
        stderr: result.stderr.trim(),
        savings,
      };
    } catch (error) {
      logger.error(`✗ RTK execution failed: ${error.message}`);
      return {
        success: false,
        stderr: error.message,
        savings: 0,
      };
    }
  }

  /**
   * Parse savings percentage from RTK output
   */
  parseSavings(output) {
    const match = output.match(/-\s*(\d+)%\s+savings?/i);
    return match ? parseInt(match[1], 10) : 0;
  }

  /**
   * Get RTK tracking statistics
   */
  async getTrackingStats() {
    if (!this.enabled) {
      return null;
    }

    try {
      const { execa } = await import('execa');
      const result = await execa(this.rtkPath, ['gain']);

      return {
        totalCommands: result.stdout.match(/Commands run: (\d+)/)?.[1] || '0',
        totalSavings: result.stdout.match(/Total savings: (\d+%)/)?.[1] || '0%',
        history: result.stdout,
      };
    } catch (error) {
      logger.error(`✗ Failed to get RTK tracking stats: ${error.message}`);
      return null;
    }
  }

  /**
   * List supported commands
   */
  async listSupportedCommands() {
    if (!this.enabled) {
      return [];
    }

    try {
      const { execa } = await import('execa');
      const result = await execa(this.rtkPath, ['--help']);

      // Parse help output to extract supported commands
      const lines = result.stdout.split('\n');
      const supportedCommands = lines
        .filter(line => line.match(/^\s+[a-z]+/))
        .map(line => line.trim().split(/\s+/)[0]);

      return supportedCommands;
    } catch (error) {
      logger.error(`✗ Failed to list supported commands: ${error.message}`);
      return [];
    }
  }
}

// Singleton instance
let rtkInstance = null;

export function getRTK() {
  if (!rtkInstance) {
    rtkInstance = new RTKIntegration();
  }
  return rtkInstance;
}
