File size: 30,442 Bytes
a718a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
package com.anthony.failsafeapi.service;

import com.anthony.failsafeapi.event.AiCallEvent;
import com.anthony.failsafeapi.exception.AIModelCallException;
import com.anthony.failsafeapi.exception.AIResponseParseException;
import com.anthony.failsafeapi.model.ProcessingContext;
import com.anthony.failsafeapi.model.TicketResponse;
import com.anthony.failsafeapi.util.constants.AuditStatus;
import com.anthony.failsafeapi.util.constants.ProcessingStatus;
import com.anthony.failsafeapi.config.GeminiConfig;
import com.anthony.failsafeapi.config.GroqConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.micrometer.core.instrument.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.metadata.ChatResponseMetadata;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.context.ApplicationEventPublisher;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

import java.math.BigDecimal;
import java.util.function.Consumer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

/**
 * Tests unitarios para AiEngineService.
 *
 * Estrategia de mocking para ChatClient (Spring AI 1.1.4):
 * El API de ChatClient usa un builder fluent con varios tipos intermedios.
 * Creamos un helper setupChatClientChain() que mockea toda la cadena
 * para que cada test solo configure lo que le importa.
 *
 * Cadena completa:
 *   chatClient.prompt()
 *     β†’ ChatClientRequestSpec
 *     .system(Consumer<SystemSpec>)
 *     β†’ ChatClientRequestSpec
 *     .user(String)
 *     β†’ ChatClientRequestSpec
 *     .call()
 *     β†’ CallResponseSpec
 *     .chatResponse()
 *     β†’ ChatResponse
 */
@ExtendWith(MockitoExtension.class)
@DisplayName("AiEngineService - Motor de clasificaciΓ³n con IA")
class AiEngineServiceTest {

    // ── Dependencias del servicio ──────────────────────────────────────────────

    @Mock
    private ChatClient chatClient;
    @Mock
    private ChatClient geminiChatClient;
    @Mock
    private GroqConfig groqConfig;
    @Mock
    private GeminiConfig geminiConfig;
    private SimpleMeterRegistry meterRegistry;
    @Mock
    private InferenceSecurityService aiLocal;
    @Mock
    private PromptCacheService promptCacheService;
    @Mock
    private ApplicationEventPublisher eventPublisher;
    @Mock
    private CircuitBreakerRegistry circuitBreakerRegistry;

    // ── Mocks de la cadena fluent de ChatClient ────────────────────────────────

    @Mock
    private ChatClient.ChatClientRequestSpec groqRequestSpec;
    @Mock
    private ChatClient.CallResponseSpec groqCallSpec;
    @Mock
    private ChatClient.ChatClientRequestSpec geminiRequestSpec;
    @Mock
    private ChatClient.CallResponseSpec geminiCallSpec;

    // ── Circuit Breakers ──────────────────────────────────────────────────────

    @Mock
    private CircuitBreaker groqCircuitBreaker;
    @Mock
    private CircuitBreaker geminiCircuitBreaker;

    // ── Sistema bajo prueba ───────────────────────────────────────────────────

    private AiEngineService aiEngineService;

    // ── JSON mΓ­nimo vΓ‘lido que el BeanOutputConverter puede parsear ────────────
    private static final String VALID_JSON_RESPONSE = """
            {
              "category": "URGENTE",
              "provider": "groq/llama",
              "status": "SUCCESS",
              "inputTokens": 100,
              "outputTokens": 50,
              "estimatedCostUsd": 0.00001,
              "latencyMs": 300,
              "piiDetected": false,
              "securityLayersPassed": [],
              "securityLayersWithTiming": [],
              "maskedDescription": "texto",
              "processedAt": "2024-01-01T00:00:00Z",
              "circuitBreakerState": "CLOSED"
            }
            """;

    @BeforeEach
    void setUp() {
        meterRegistry = new SimpleMeterRegistry();
        // ConstrucciΓ³n manual porque @InjectMocks no distingue los dos ChatClient
        aiEngineService = new AiEngineService(
                chatClient,
                geminiChatClient,
                geminiConfig,
                meterRegistry,
                aiLocal,
                promptCacheService,
                groqConfig,
                eventPublisher,
                circuitBreakerRegistry
        );


        // Circuit Breaker de Groq por defecto
        lenient().when(circuitBreakerRegistry.circuitBreaker("aiClassification"))
                .thenReturn(groqCircuitBreaker);
        lenient().when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.CLOSED);

        // Circuit Breaker de Gemini por defecto
        lenient().when(circuitBreakerRegistry.circuitBreaker("geminiClassification"))
                .thenReturn(geminiCircuitBreaker);
        lenient().when(geminiCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.CLOSED);
    }

    // ═════════════════════════════════════════════════════════════════════════
    // HELPERS
    // ═════════════════════════════════════════════════════════════════════════

    /**
     * Monta la cadena fluent de Groq ChatClient para que devuelva el texto dado.
     */
    private void setupGroqChain(String responseText) {
        ChatResponse chatResponse = buildChatResponse(responseText, 100, 50);

        when(chatClient.prompt()).thenReturn(groqRequestSpec);
        when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec);
        when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec);
        when(groqRequestSpec.call()).thenReturn(groqCallSpec);
        when(groqCallSpec.chatResponse()).thenReturn(chatResponse);
    }

    /**
     * Monta la cadena fluent de Gemini ChatClient para que devuelva el texto dado.
     */
    private void setupGeminiChain(String responseText) {
        ChatResponse chatResponse = buildChatResponse(responseText, 80, 40);

        when(geminiChatClient.prompt()).thenReturn(geminiRequestSpec);
        when(geminiRequestSpec.system(any(Consumer.class))).thenReturn(geminiRequestSpec);
        when(geminiRequestSpec.user(anyString())).thenReturn(geminiRequestSpec);
        when(geminiRequestSpec.call()).thenReturn(geminiCallSpec);
        when(geminiCallSpec.chatResponse()).thenReturn(chatResponse);
    }

    /**
     * Construye un ChatResponse con los tokens y texto dados.
     * Usa mocks porque ChatResponse no tiene constructor pΓΊblico directo.
     */
    private ChatResponse buildChatResponse(String text, int inputTokens, int outputTokens) {
        ChatResponse response = mock(ChatResponse.class);
        Generation generation = mock(Generation.class);
        AssistantMessage assistantMessage = mock(AssistantMessage.class);
        ChatResponseMetadata metadata = mock(ChatResponseMetadata.class);
        Usage usage = mock(Usage.class);

        when(response.getResult()).thenReturn(generation);
        when(generation.getOutput()).thenReturn(assistantMessage);
        when(assistantMessage.getText()).thenReturn(text);
        when(response.getMetadata()).thenReturn(metadata);
        when(metadata.getUsage()).thenReturn(usage);
        when(usage.getPromptTokens()).thenReturn(inputTokens);
        when(usage.getCompletionTokens()).thenReturn(outputTokens);

        return response;
    }

    /**
     * Configura los configs de Groq con valores por defecto para tests.
     */
    private void setupGroqConfig() {
        lenient().when(groqConfig.getModel()).thenReturn("groq/llama");
        lenient().when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.05"));
        lenient().when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.10"));
    }

    /**
     * Configura los configs de Gemini con valores por defecto para tests.
     */
    private void setupGeminiConfig() {
        lenient().when(geminiConfig.getModel()).thenReturn("gemini-2.5-flash");
        lenient().when(geminiConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.01"));
        lenient().when(geminiConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.02"));
    }

    private ProcessingContext buildContext() {
        return new ProcessingContext();
    }

    // ═════════════════════════════════════════════════════════════════════════
    // LLAMADA EXITOSA A GROQ
    // ═════════════════════════════════════════════════════════════════════════

    @Nested
    @DisplayName("callLlm β€” Llamada exitosa a Groq")
    class CallLlmSuccessTests {

        @BeforeEach
        void setUp() {
            when(promptCacheService.getPrompt()).thenReturn("system prompt template {format}");
            setupGroqConfig();
        }

        @Test
        @DisplayName("Devuelve TicketResponse con categorΓ­a correcta cuando Groq responde")
        void shouldReturnTicketResponseWithCorrectCategory() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("Mi pedido llegΓ³ roto", buildContext());

            assertThat(result).isNotNull();
            assertThat(result.category()).isEqualTo("URGENTE");
            assertThat(result.status()).isEqualTo(ProcessingStatus.SUCCESS.name());
            verifyNoInteractions(geminiChatClient);
        }

        @Test
        @DisplayName("El provider en la respuesta es el del config de Groq")
        void shouldUseGroqModelAsProvider() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.provider()).isEqualTo("groq/llama");
        }

        @Test
        @DisplayName("Los tokens de entrada y salida se asignan correctamente")
        void shouldSetInputAndOutputTokens() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.inputTokens()).isEqualTo(100);
            assertThat(result.outputTokens()).isEqualTo(50);
        }

        @Test
        @DisplayName("El costo estimado es mayor que cero cuando hay tokens")
        void shouldCalculatePositiveCost() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.estimatedCostUsd()).isGreaterThan(BigDecimal.ZERO);
        }

        @Test
        @DisplayName("La latencia es mayor o igual a cero")
        void shouldHaveNonNegativeLatency() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.latencyMs()).isGreaterThanOrEqualTo(0L);
        }

        @Test
        @DisplayName("Publica un AiCallEvent con status SUCCESS al completar")
        void shouldPublishSuccessEvent() {
            setupGroqChain(VALID_JSON_RESPONSE);

            aiEngineService.callLlm("descripciΓ³n", buildContext());

            ArgumentCaptor<AiCallEvent> eventCaptor = ArgumentCaptor.forClass(AiCallEvent.class);
            verify(eventPublisher).publishEvent(eventCaptor.capture());

            AiCallEvent event = eventCaptor.getValue();
            assertThat(event.status()).isEqualTo(AuditStatus.SUCCESS);
            assertThat(event.provider()).isEqualTo("groq/llama");
        }

        @Test
        @DisplayName("El estado del circuit breaker se refleja en la respuesta")
        void shouldReflectCircuitBreakerState() {
            setupGroqChain(VALID_JSON_RESPONSE);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.circuitBreakerState()).isEqualTo("CLOSED");
        }

        @Test
        @DisplayName("Propaga datos del ProcessingContext en la respuesta")
        void shouldPropagateProcessingContextData() {
            setupGroqChain(VALID_JSON_RESPONSE);
            ProcessingContext ctx = buildContext();
            ctx.markPiiDetected();
            ctx.setMaskedDescription("texto con [EMAIL]");

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", ctx);

            assertThat(result.piiDetected()).isTrue();
            assertThat(result.maskedDescription()).isEqualTo("texto con [EMAIL]");
        }

        @Test
        @DisplayName("El JSON con markdown fence es extraΓ­do y parseado correctamente")
        void shouldExtractJsonFromMarkdownFence() {
            String withFence = "```json\n" + VALID_JSON_RESPONSE + "\n```";
            setupGroqChain(withFence);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.category()).isEqualTo("URGENTE");
        }

        @Test
        @DisplayName("El JSON con texto antes y despuΓ©s es extraΓ­do correctamente")
        void shouldExtractJsonWithSurroundingText() {
            String withText = "AquΓ­ estΓ‘ la clasificaciΓ³n:\n" + VALID_JSON_RESPONSE + "\nEspero que ayude.";
            setupGroqChain(withText);

            TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

            assertThat(result.category()).isEqualTo("URGENTE");
        }
    }

    // ═════════════════════════════════════════════════════════════════════════
    // ERRORES EN LLAMADA A GROQ
    // ═════════════════════════════════════════════════════════════════════════

    @Nested
    @DisplayName("callLlm β€” Errores en llamada a Groq")
    class CallLlmErrorTests {

        @BeforeEach
        void setUp() {
            when(promptCacheService.getPrompt()).thenReturn("system prompt {format}");
            setupGroqConfig();
        }

        @Test
        @DisplayName("Lanza AIModelCallException cuando la llamada HTTP a Groq falla")
        void shouldThrowAIModelCallExceptionOnHttpFailure() {
            when(chatClient.prompt()).thenReturn(groqRequestSpec);
            when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec);
            when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec);
            when(groqRequestSpec.call()).thenThrow(new RuntimeException("Connection refused"));

            assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext()))
                    .isInstanceOf(AIModelCallException.class)
                    .hasMessageContaining("Error llamando al LLM externo");
        }

        @Test
        @DisplayName("Lanza AIResponseParseException cuando el prompt no se puede cargar")
        void shouldThrowAIResponseParseExceptionWhenPromptFails() {
            when(promptCacheService.getPrompt()).thenThrow(new RuntimeException("File not found"));

            assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext()))
                    .isInstanceOf(AIResponseParseException.class)
                    .hasMessageContaining("Error cargando la plantilla del prompt");
        }

        @Test
        @DisplayName("Registra mΓ©trica de error cuando la llamada HTTP falla")
        void shouldRecordErrorMetricOnHttpFailure() {
            when(chatClient.prompt()).thenReturn(groqRequestSpec);
            when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec);
            when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec);
            when(groqRequestSpec.call()).thenThrow(new RuntimeException("timeout"));

            assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext()))
                    .isInstanceOf(AIModelCallException.class);

            // Verificamos que la mΓ©trica se registrΓ³ realmente en el registry
            // (no solo que se llamΓ³ al mΓ©todo). SimpleMeterRegistry mantiene todo en memoria.
            Timer errorTimer = meterRegistry.find("ai.call.latency")
                    .tag("provider", "groq")
                    .tag("status", "error")
                    .timer();

            assertThat(errorTimer).isNotNull();
            assertThat(errorTimer.count()).isEqualTo(1);
        }

        // ═════════════════════════════════════════════════════════════════════════
        // FALLBACK β€” GROQ FALLA β†’ GEMINI
        // ═════════════════════════════════════════════════════════════════════════

        @Nested
        @DisplayName("fallbackClassify β€” Cascada Groq β†’ Gemini")
        class FallbackToGeminiTests {

            @BeforeEach
            void setUp() {
                when(promptCacheService.getPrompt()).thenReturn("system prompt {format}");
                setupGeminiConfig();
            }

            @Test
            @DisplayName("Cuando Groq falla, el fallback llama a Gemini y devuelve su respuesta")
            void shouldCallGeminiWhenGroqFails() {
                String geminiJson = VALID_JSON_RESPONSE
                        .replace("\"URGENTE\"", "\"NORMAL\"")
                        .replace("\"groq/llama\"", "\"gemini-2.5-flash\"");

                setupGeminiChain(geminiJson);

                when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> {
                    java.util.function.Supplier<?> supplier = inv.getArgument(0);
                    return supplier.get();
                });

                TicketResponse result = aiEngineService.fallbackClassify(
                        "descripciΓ³n",
                        buildContext(),
                        new AIModelCallException("Groq down", new RuntimeException())
                );

                assertThat(result).isNotNull();
                assertThat(result.category()).isEqualTo("NORMAL");
                assertThat(result.provider()).isEqualTo("gemini-2.5-flash");
            }

            @Test
            @DisplayName("El provider en la respuesta de Gemini es el del config de Gemini")
            void shouldUseGeminiModelAsProvider() {
                String jsonSinProvider = """
                        {
                          "category": "URGENTE",
                          "status": "SUCCESS",
                          "inputTokens": 100,
                          "outputTokens": 50,
                          "estimatedCostUsd": 0.00001,
                          "latencyMs": 300,
                          "piiDetected": false,
                          "securityLayersPassed": [],
                          "securityLayersWithTiming": [],
                          "maskedDescription": "texto",
                          "processedAt": "2024-01-01T00:00:00Z",
                          "circuitBreakerState": "CLOSED"
                        }
                        """;

                setupGeminiChain(jsonSinProvider);

                when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> {
                    java.util.function.Supplier<?> supplier = inv.getArgument(0);
                    return supplier.get();
                });

                TicketResponse result = aiEngineService.fallbackClassify(
                        "descripciΓ³n",
                        buildContext(),
                        new AIModelCallException("error", new RuntimeException())
                );

                assertThat(result.provider()).isEqualTo("gemini-2.5-flash");
            }

            @Test
            @DisplayName("Publica un AiCallEvent con status SUCCESS cuando Gemini responde")
            void shouldPublishSuccessEventForGemini() {
                setupGeminiChain(VALID_JSON_RESPONSE);

                when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> {
                    java.util.function.Supplier<?> supplier = inv.getArgument(0);
                    return supplier.get();
                });

                aiEngineService.fallbackClassify(
                        "descripciΓ³n",
                        buildContext(),
                        new AIModelCallException("error", new RuntimeException())
                );

                ArgumentCaptor<AiCallEvent> captor = ArgumentCaptor.forClass(AiCallEvent.class);
                verify(eventPublisher).publishEvent(captor.capture());

                assertThat(captor.getValue().status()).isEqualTo(AuditStatus.SUCCESS);
                assertThat(captor.getValue().provider()).isEqualTo("gemini-2.5-flash");
            }
        }

        // ═════════════════════════════════════════════════════════════════════════
        // EXTRACCIΓ“N DE JSON β€” extractJson
        // ═════════════════════════════════════════════════════════════════════════

        @Nested
        @DisplayName("callLlm β€” ExtracciΓ³n de JSON de respuestas con formato variable")
        class JsonExtractionTests {

            @BeforeEach
            void setUp() {
                when(promptCacheService.getPrompt()).thenReturn("prompt {format}");
                setupGroqConfig();
            }

            @Test
            @DisplayName("Parsea JSON envuelto en bloque de cΓ³digo sin lenguaje")
            void shouldParseJsonInCodeBlockWithoutLanguage() {
                String withFenceNoLang = "```\n" + VALID_JSON_RESPONSE + "\n```";
                setupGroqChain(withFenceNoLang);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());
                assertThat(result.category()).isEqualTo("URGENTE");
            }

            @Test
            @DisplayName("Parsea JSON cuando el modelo incluye texto explicativo antes")
            void shouldParseJsonWithPreamble() {
                String withPreamble = "La categorΓ­a del ticket es:\n" + VALID_JSON_RESPONSE;
                setupGroqChain(withPreamble);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());
                assertThat(result.category()).isEqualTo("URGENTE");
            }
        }

        // ═════════════════════════════════════════════════════════════════════════
        // ESTADO DEL CIRCUIT BREAKER
        // ═════════════════════════════════════════════════════════════════════════

        @Nested
        @DisplayName("Estado del Circuit Breaker en la respuesta")
        class CircuitBreakerStateTests {

            @BeforeEach
            void setUp() {
                when(promptCacheService.getPrompt()).thenReturn("prompt {format}");
                setupGroqConfig();
            }

            @Test
            @DisplayName("Refleja OPEN cuando el circuit breaker de Groq estΓ‘ abierto")
            void shouldReflectOpenState() {
                when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.OPEN);
                setupGroqChain(VALID_JSON_RESPONSE);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

                assertThat(result.circuitBreakerState()).isEqualTo("OPEN");
            }

            @Test
            @DisplayName("Refleja HALF_OPEN cuando el circuit breaker estΓ‘ en recuperaciΓ³n")
            void shouldReflectHalfOpenState() {
                when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.HALF_OPEN);
                setupGroqChain(VALID_JSON_RESPONSE);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

                assertThat(result.circuitBreakerState()).isEqualTo("HALF_OPEN");
            }

            @Test
            @DisplayName("Devuelve UNKNOWN cuando el circuit breaker no existe en el registro")
            void shouldReturnUnknownWhenCircuitBreakerNotFound() {
                when(circuitBreakerRegistry.circuitBreaker("aiClassification"))
                        .thenThrow(new RuntimeException("Not registered"));
                setupGroqChain(VALID_JSON_RESPONSE);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

                assertThat(result.circuitBreakerState()).isEqualTo("UNKNOWN");
            }
        }

        // ═════════════════════════════════════════════════════════════════════════
        // CÁLCULO DE COSTOS
        // ═════════════════════════════════════════════════════════════════════════

        @Nested
        @DisplayName("CΓ‘lculo de costos de tokens")
        class CostCalculationTests {

            @BeforeEach
            void setUp() {
                when(promptCacheService.getPrompt()).thenReturn("prompt {format}");
            }

            @Test
            @DisplayName("El costo es cero cuando los tokens son cero")
            void costShouldBeZeroWhenTokensAreZero() {
                when(groqConfig.getModel()).thenReturn("groq/llama");
                when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.05"));
                when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.10"));

                // Respuesta con 0 tokens
                ChatResponse response = mock(ChatResponse.class);
                Generation generation = mock(Generation.class);
                AssistantMessage msg = mock(AssistantMessage.class);
                ChatResponseMetadata metadata = mock(ChatResponseMetadata.class);
                Usage usage = mock(Usage.class);

                when(response.getResult()).thenReturn(generation);
                when(generation.getOutput()).thenReturn(msg);
                when(msg.getText()).thenReturn(VALID_JSON_RESPONSE);
                when(response.getMetadata()).thenReturn(metadata);
                when(metadata.getUsage()).thenReturn(usage);
                when(usage.getPromptTokens()).thenReturn(0);
                when(usage.getCompletionTokens()).thenReturn(0);

                when(chatClient.prompt()).thenReturn(groqRequestSpec);
                when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec);
                when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec);
                when(groqRequestSpec.call()).thenReturn(groqCallSpec);
                when(groqCallSpec.chatResponse()).thenReturn(response);

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

                assertThat(result.estimatedCostUsd()).isEqualByComparingTo(BigDecimal.ZERO);
            }

            @Test
            @DisplayName("El costo se calcula correctamente con precio conocido")
            void shouldCalculateCostCorrectly() {
                // 1_000_000 tokens a $1.00/millΓ³n = $1.00
                // Para 100 tokens input a $1.00/M y 50 tokens output a $2.00/M:
                // inputCost  = 100 / 1_000_000 * 1.00 = 0.0001
                // outputCost = 50  / 1_000_000 * 2.00 = 0.0001
                // total = 0.0002
                when(groqConfig.getModel()).thenReturn("groq/llama");
                when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("1.00"));
                when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("2.00"));

                setupGroqChain(VALID_JSON_RESPONSE); // 100 input, 50 output

                TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext());

                assertThat(result.estimatedCostUsd())
                        .isEqualByComparingTo(new BigDecimal("0.0002"));
            }
        }
    }
}