# Artillery Load Testing Configuration for Google Services Integration
# 
# Comprehensive load testing scenarios for Google AI services with
# realistic traffic patterns, gradual ramp-up, and stress testing.

config:
  target: "{{ $processEnvironment.BASE_URL || 'http://localhost:8080' }}"
  phases:
    # Warm-up phase
    - duration: 60
      arrivalRate: 2
      name: "Warm-up"
    
    # Gradual ramp-up
    - duration: 300
      arrivalRate: 5
      rampTo: 20
      name: "Ramp-up"
    
    # Sustained load
    - duration: 600
      arrivalRate: 20
      name: "Sustained load"
    
    # Spike test
    - duration: 120
      arrivalRate: 50
      name: "Spike test"
    
    # Cool-down
    - duration: 180
      arrivalRate: 50
      rampTo: 5
      name: "Cool-down"
  
  # Global request configuration
  defaults:
    headers:
      Content-Type: "application/json"
      User-Agent: "Artillery-GoogleServices-LoadTest/1.0"
      x-api-key: "{{ $processEnvironment.API_KEY || 'mock-api-key' }}"
  
  # Performance thresholds
  ensure:
    p95: 2000  # 95% of requests should complete within 2 seconds
    p99: 5000  # 99% of requests should complete within 5 seconds
    maxErrorRate: 5  # Maximum 5% error rate
  
  # Plugins configuration
  plugins:
    metrics-by-endpoint:
      useOnlyRequestNames: true
    
  # Custom metrics
  engines:
    http:
      timeout: 30
      pool: 50
      maxSockets: 100
  
  # Variables for test data
  variables:
    videoPrompts:
      - "Create a professional product demonstration"
      - "Generate a cinematic landscape sequence"
      - "Produce an animated explainer video"
      - "Create a time-lapse construction video"
      - "Generate a corporate presentation"
    
    imagePrompts:
      - "Generate a high-resolution product photo"
      - "Create a technical diagram illustration"
      - "Produce a scientific research figure"
      - "Generate a marketing banner design"
      - "Create an infographic visualization"
    
    audioTexts:
      - "Welcome to our professional AI platform demonstration"
      - "This is a comprehensive overview of our services"
      - "Let me guide you through the key features"
      - "Thank you for your attention and interest"
      - "For more information, please contact our team"
    
    musicStyles:
      - "corporate"
      - "cinematic"
      - "uplifting"
      - "dramatic"
      - "ambient"
    
    qualities:
      - "low"
      - "medium"
      - "high"
    
    resolutions:
      - { width: 512, height: 512 }
      - { width: 1024, height: 1024 }
      - { width: 1920, height: 1080 }
    
    voices:
      - "professional"
      - "conversational"
      - "narrator"

scenarios:
  # Streaming API Load Test
  - name: "Streaming API Load Test"
    weight: 30
    flow:
      # Create streaming session
      - post:
          url: "/v1/streaming/sessions"
          name: "Create streaming session"
          json:
            type: "multimodal"
            userId: "load-test-user-{{ $uuid }}"
            userPreferences:
              qualityPriority: "balanced"
            deviceCapabilities:
              cpu:
                cores: 4
            networkConditions:
              bandwidth:
                download: 10000000
          capture:
            json: "$.data.id"
            as: "sessionId"
          expect:
            - statusCode: 200
            - hasProperty: "success"
      
      # Start video stream
      - post:
          url: "/v1/streaming/sessions/{{ sessionId }}/video"
          name: "Start video stream"
          json:
            id: "stream-{{ $uuid }}"
            source: "camera"
            quality:
              level: "{{ $randomString(qualities) }}"
            constraints:
              video:
                width:
                  ideal: 1280
                height:
                  ideal: 720
          expect:
            - statusCode: 200
            - hasProperty: "success"
      
      # Simulate streaming duration
      - think: 3
      
      # Start audio stream
      - post:
          url: "/v1/streaming/sessions/{{ sessionId }}/audio"
          name: "Start audio stream"
          json:
            id: "audio-{{ $uuid }}"
            source: "microphone"
            quality:
              level: "{{ $randomString(qualities) }}"
            processing:
              noiseReduction: true
              echoCancellation: true
          expect:
            - statusCode: 200
            - hasProperty: "success"
      
      # Simulate streaming session
      - think: 5
      
      # End streaming session
      - delete:
          url: "/v1/streaming/sessions/{{ sessionId }}"
          name: "End streaming session"
          expect:
            - statusCode: 200
  
  # Video Generation Stress Test
  - name: "Video Generation Stress Test"
    weight: 25
    flow:
      # Generate video
      - post:
          url: "/v1/video:generate"
          name: "Generate video"
          json:
            prompt: "{{ $randomString(videoPrompts) }}"
            duration: "{{ $randomNumber(5000, 15000) }}"
            quality: "{{ $randomString(qualities) }}"
            style:
              type: "realistic"
              mood: "professional"
          capture:
            json: "$.data.videoId"
            as: "videoId"
          expect:
            - statusCode: 200
            - hasProperty: "success"
      
      # Poll for completion
      - loop:
          count: 15
          over:
            - get:
                url: "/v1/video/{{ videoId }}/status"
                name: "Check video status"
                capture:
                  json: "$.status"
                  as: "videoStatus"
            
            - think: 2
            
            # Break if completed
            - ifTrue: "videoStatus === 'completed'"
              then:
                - get:
                    url: "/v1/video/{{ videoId }}/download"
                    name: "Download video"
                    expect:
                      - statusCode: 200
                      - contentType: "video/mp4"
                - break: true
            
            # Break if failed
            - ifTrue: "videoStatus === 'failed'"
              then:
                - break: true
  
  # Image Generation Burst Test
  - name: "Image Generation Burst Test"
    weight: 25
    flow:
      # Generate multiple images in quick succession
      - loop:
          count: 3
          over:
            - post:
                url: "/v1/images:generate"
                name: "Generate image"
                json:
                  prompt: "{{ $randomString(imagePrompts) }}"
                  style: "realistic"
                  format: "png"
                  dimensions: "{{ $randomString(resolutions) }}"
                capture:
                  json: "$.data.imageId"
                  as: "imageId"
                expect:
                  - statusCode: 200
                  - hasProperty: "success"
            
            # Download generated image
            - get:
                url: "/v1/images/{{ imageId }}"
                name: "Download image"
                expect:
                  - statusCode: 200
                  - contentType: /image\/.*/
            
            - think: 1
  
  # Audio Processing Load Test
  - name: "Audio Processing Load Test"
    weight: 15
    flow:
      # Speech synthesis
      - post:
          url: "/v1/speech:synthesize"
          name: "Synthesize speech"
          json:
            text: "{{ $randomString(audioTexts) }}"
            voice: "{{ $randomString(voices) }}"
            language: "en-US"
            speed: 1.0
            emotion: "confident"
          expect:
            - statusCode: 200
            - hasProperty: "success"
            - hasProperty: "data.audioContent"
      
      - think: 2
      
      # Music generation
      - post:
          url: "/v1/music:generate"
          name: "Generate music"
          json:
            style: "{{ $randomString(musicStyles) }}"
            mood: "professional"
            duration: "{{ $randomNumber(10000, 30000) }}"
            instruments:
              - "piano"
              - "strings"
            tempo: "{{ $randomNumber(80, 140) }}"
          capture:
            json: "$.data.musicId"
            as: "musicId"
          expect:
            - statusCode: 200
            - hasProperty: "success"
      
      # Poll for music completion
      - loop:
          count: 10
          over:
            - get:
                url: "/v1/music/{{ musicId }}/status"
                name: "Check music status"
                capture:
                  json: "$.status"
                  as: "musicStatus"
            
            - think: 3
            
            # Break if completed or failed
            - ifTrue: "musicStatus === 'completed' || musicStatus === 'failed'"
              then:
                - break: true
  
  # Mixed Workload Test
  - name: "Mixed Workload Test"
    weight: 5
    flow:
      # Random selection of operations
      - function: "selectRandomWorkload"
      
      # Execute based on selection
      - ifTrue: "workloadType === 'streaming'"
        then:
          - post:
              url: "/v1/streaming/sessions"
              name: "Mixed: Create session"
              json:
                type: "video"
                userId: "mixed-user-{{ $uuid }}"
              capture:
                json: "$.data.id"
                as: "mixedSessionId"
          
          - think: 2
          
          - delete:
              url: "/v1/streaming/sessions/{{ mixedSessionId }}"
              name: "Mixed: End session"
      
      - ifTrue: "workloadType === 'generation'"
        then:
          - post:
              url: "/v1/images:generate"
              name: "Mixed: Generate image"
              json:
                prompt: "{{ $randomString(imagePrompts) }}"
                style: "artistic"
                format: "jpg"
              capture:
                json: "$.data.imageId"
                as: "mixedImageId"
          
          - get:
              url: "/v1/images/{{ mixedImageId }}"
              name: "Mixed: Download image"

# Custom functions for advanced scenarios
functions:
  selectRandomWorkload: |
    function(context, events, done) {
      const workloads = ['streaming', 'generation', 'audio'];
      context.vars.workloadType = workloads[Math.floor(Math.random() * workloads.length)];
      return done();
    }
  
  calculateResponseTime: |
    function(context, events, done) {
      const startTime = context.vars.requestStart;
      const endTime = Date.now();
      context.vars.responseTime = endTime - startTime;
      return done();
    }
  
  validateVideoQuality: |
    function(context, events, done) {
      const response = context.vars.$;
      if (response && response.data && response.data.quality) {
        context.vars.qualityValid = true;
      } else {
        context.vars.qualityValid = false;
      }
      return done();
    }

# Custom processors for metrics collection
processors:
  # Log custom metrics
  logMetrics: |
    function(req, res, context, ee, next) {
      if (res.statusCode >= 400) {
        console.log(`Error ${res.statusCode}: ${req.url}`);
      }
      
      if (context.vars.responseTime > 5000) {
        console.log(`Slow response: ${context.vars.responseTime}ms for ${req.url}`);
      }
      
      return next();
    }
  
  # Track generation metrics
  trackGeneration: |
    function(req, res, context, ee, next) {
      if (req.url.includes('generate')) {
        const metric = {
          timestamp: Date.now(),
          url: req.url,
          duration: context.vars.responseTime,
          status: res.statusCode
        };
        
        console.log(`Generation metric: ${JSON.stringify(metric)}`);
      }
      
      return next();
    }
  
  # Monitor streaming sessions
  monitorStreaming: |
    function(req, res, context, ee, next) {
      if (req.url.includes('streaming/sessions')) {
        if (req.method === 'POST') {
          context.vars.streamStartTime = Date.now();
        } else if (req.method === 'DELETE') {
          const streamDuration = Date.now() - (context.vars.streamStartTime || 0);
          console.log(`Stream duration: ${streamDuration}ms`);
        }
      }
      
      return next();
    }
