// WAPL Pattern Compiler Service

import { WAPLPattern, PatternCondition } from './types';
import { logger } from '@/infrastructure/monitoring/logger';

export class PatternCompilerService {
  /**
   * Compile pattern definition to executable conditions
   */
  compilePattern(pattern: WAPLPattern): PatternCondition[] {
    try {
      // Parse pattern definition
      // Example: "if occurs(FX_trade[X].pair == FX_trade[Y].pair.reverse && abs(FX_trade[X].amount - FX_trade[Y].amount) < tolerance)"
      
      const conditions: PatternCondition[] = [];

      // Simple pattern parsing (in production, use a proper parser)
      if (pattern.patternDefinition.includes('FX_trade')) {
        conditions.push({
          type: 'FX_TRADE',
          operator: 'OCCURS',
          value: true,
        });
      }

      if (pattern.patternDefinition.includes('velocity')) {
        conditions.push({
          type: 'VELOCITY',
          operator: 'GREATER_THAN',
          value: this.extractThreshold(pattern.patternDefinition),
        });
      }

      if (pattern.patternDefinition.includes('hops')) {
        conditions.push({
          type: 'HOP_COUNT',
          operator: 'GREATER_THAN',
          value: this.extractHopCount(pattern.patternDefinition),
        });
      }

      logger.info(`Compiled pattern ${pattern.patternCode}`, {
        conditionsCount: conditions.length,
      });

      return conditions;
    } catch (error) {
      logger.error(`Failed to compile pattern ${pattern.patternCode}`, error);
      return [];
    }
  }

  /**
   * Extract threshold from pattern definition
   */
  private extractThreshold(definition: string): number {
    const match = definition.match(/threshold[:\s]*(\d+)/i);
    return match ? parseInt(match[1]) : 10;
  }

  /**
   * Extract hop count from pattern definition
   */
  private extractHopCount(definition: string): number {
    const match = definition.match(/hops[:\s]*>\s*(\d+)/i);
    return match ? parseInt(match[1]) : 4;
  }

  /**
   * Validate pattern syntax
   */
  validatePattern(pattern: WAPLPattern): { valid: boolean; errors: string[] } {
    const errors: string[] = [];

    if (!pattern.patternCode) {
      errors.push('Pattern code is required');
    }

    if (!pattern.patternDefinition) {
      errors.push('Pattern definition is required');
    }

    if (!pattern.name) {
      errors.push('Pattern name is required');
    }

    // Basic syntax validation
    if (pattern.patternDefinition && !pattern.patternDefinition.includes('if')) {
      errors.push('Pattern definition must contain "if" statement');
    }

    return {
      valid: errors.length === 0,
      errors,
    };
  }
}

export const patternCompilerService = new PatternCompilerService();

