api_claude 0.4.0

Claude API for accessing Anthropic's large language models (LLMs).
Documentation
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Error Handling Integration Tests - STRICT FAILURE POLICY
//!
//! # Knowledge : Error Classification & Recovery Strategy
//!
//! ## Why Error Classification Matters
//!
//! Different errors require different handling strategies. Classification enables:
//! - **Retry Decisions**: Transient errors (rate limit, network) should retry; permanent errors (auth, invalid params) should not
//! - **User Guidance**: Each error type has specific recovery actions users can take
//! - **Monitoring**: Error severity helps prioritize incident response
//! - **Circuit Breaker Integration**: Transient errors trigger circuit breaker; client errors do not
//!
//! ## Error Severity Levels (Operational Impact)
//!
//! - **Critical**: Blocks all operations, requires immediate action (Authentication, MissingEnvironment)
//!   - Impact : Cannot proceed with ANY requests
//!   - Recovery : Fix credentials/environment before retrying
//!
//! - **High**: Blocks current operation, likely user error (InvalidRequest, InvalidArgument)
//!   - Impact : This specific request fails
//!   - Recovery : Fix request parameters and retry
//!
//! - **Medium**: Temporary operational issue (RateLimit, Internal)
//!   - Impact : Request fails but system healthy
//!   - Recovery : Wait and retry with backoff
//!
//! - **Low**: Degraded functionality (Parsing, Stream interruption)
//!   - Impact : Partial failure, may have partial data
//!   - Recovery : Retry or use partial results
//!
//! ## Retryable vs Non-Retryable Errors
//!
//! **Retryable** (transient, may succeed on retry):
//! - RateLimit : Server explicitly says retry later
//! - Internal : Server-side issue, may be resolved
//! - Stream : Network interruption, connection may recover
//! - Http : Network issues are often transient
//!
//! **Non-Retryable** (permanent, will fail again):
//! - Authentication : Invalid credentials won't fix themselves
//! - InvalidArgument : Bad input won't become valid
//! - InvalidRequest : Malformed request structure permanent
//! - Parsing : If we can't parse, retrying won't help
//! - MissingEnvironment : Config issue must be fixed manually
//!
//! ## SSE Parsing Edge Cases
//!
//! **Malformed JSON** (test_sse_parsing_errors_malformed_json):
//! - Real-world scenario : Network corruption, truncated responses
//! - Strategy : Filter out bad events, continue processing stream
//! - Rationale : Partial data better than complete failure
//!
//! **Unknown Event Types** (test_sse_parsing_unknown_event_type):
//! - Real-world scenario : API adds new events before client update
//! - Strategy : Silently ignore unknown events
//! - Rationale : Forward compatibility, don't break on API evolution
//!
//! **Incomplete Data** (test_sse_parsing_content_block_delta_errors):
//! - Real-world scenario : Race conditions, partial server responses
//! - Strategy : Validate required fields, skip invalid deltas
//! - Rationale : Graceful degradation over hard failures
//!
//! ## Recovery Suggestions
//!
//! Each error type provides actionable suggestions:
//! - **MissingEnvironment**: "Set ANTHROPIC_API_KEY environment variable"
//! - **Authentication**: "Verify API key is valid at console.anthropic.com"
//! - **RateLimit**: "Wait {retry_after}s before retrying" (server-provided duration)
//! - **InvalidRequest**: Specific parameter that failed validation
//!
//! ## NO MOCKING POLICY - Why Real API Testing
//!
//! Mocking creates false confidence because:
//! - **Mock Drift**: Mocks diverge from real API behavior over time
//! - **Edge Cases**: Real APIs have edge cases mocks never simulate
//! - **Protocol Details**: HTTP headers, status codes, timing - mocks oversimplify
//! - **Integration Issues**: Network, TLS, DNS - mocks hide these failure modes
//!
//! Real API testing catches:
//! - Actual rate limit behavior and header parsing
//! - Real authentication error messages
//! - Actual network timeout scenarios
//! - Real SSE stream interruption patterns
//! - API version changes and breaking changes
//!
//! # MANDATORY INTEGRATION TEST REQUIREMENTS
//!
//! - These tests use REAL Anthropic API endpoints - NO MOCKING ALLOWED
//! - Tests MUST FAIL IMMEDIATELY if API secrets are not available (no graceful fallbacks)
//! - Tests MUST FAIL IMMEDIATELY on network connectivity issues
//! - Tests MUST FAIL IMMEDIATELY on API authentication failures
//! - Tests MUST FAIL IMMEDIATELY on any API endpoint errors
//! - NO SILENT PASSES allowed when problems occur
//!
//! Run with : cargo test --features integration
//! Requires : Valid `ANTHROPIC_API_KEY` in environment or ../../secret/-secrets.sh

#[ allow( unused_imports ) ]
use super::*;

#[ tokio::test ]
async fn test_api_error_response_parsing_and_classification()
{
  // Test parsing different API error response formats
  let error_response = r#"
  {
    "error": {
      "type": "invalid_request_error",
      "message": "Your request contains invalid parameters"
    }
  }
  "#;

  let result = the_module::ErrorParser::parse_api_error( error_response );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_class(), the_module::ErrorClass::InvalidRequest );
      assert_eq!( error.severity(), the_module::ErrorSeverity::High );
      assert!( !error.is_transient() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test authentication error classification
  let auth_error_response = r#"
  {
    "error": {
      "type": "authentication_error",
      "message": "Invalid API key provided"
    }
  }
  "#;

  let result = the_module::ErrorParser::parse_api_error( auth_error_response );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_class(), the_module::ErrorClass::Authentication );
      assert!( error.requires_credential_refresh() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_http_status_code_mapping_to_error_types()
{
  // Test mapping different HTTP status codes to specific error types
  // REMOVED: create_test_client() call - not needed for mapping tests

  // Test 400 Bad Request
  let result = the_module::ErrorMapper::map_http_status( 400, "Bad Request" );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_type(), the_module::ErrorType::InvalidRequest );
      assert!( error.has_remediation_steps() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test 401 Unauthorized
  let result = the_module::ErrorMapper::map_http_status( 401, "Unauthorized" );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_type(), the_module::ErrorType::Authentication );
      assert!( error.is_credential_related() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test 429 Too Many Requests
  let result = the_module::ErrorMapper::map_http_status( 429, "Too Many Requests" );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_type(), the_module::ErrorType::RateLimit );
      assert!( error.has_backoff_strategy() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test 500 Internal Server Error
  let result = the_module::ErrorMapper::map_http_status( 500, "Internal Server Error" );
  match result
  {
    Ok( error ) =>
    {
      assert_eq!( error.error_type(), the_module::ErrorType::ServerError );
      assert!( error.is_transient() );
      assert!( error.supports_retry() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_error_context_preservation_and_stack_traces()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real error context testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_error_recovery_strategies_and_retry_conditions()
{
  // Test automatic retry condition detection
  // REMOVED: create_test_client() call - not needed for strategy tests

  // Test transient network error
  let network_error = the_module::AnthropicError::http_error( "Connection timeout".to_string() );
  let recovery_strategy = the_module::ErrorRecovery::analyze_error( &network_error );
  
  match recovery_strategy
  {
    Ok( strategy ) =>
    {
      assert!( strategy.should_retry() );
      assert_eq!( strategy.max_retries(), 3 );
      assert!( strategy.backoff_strategy() == the_module::BackoffStrategy::ExponentialBackoff );
      assert!( strategy.base_delay() > core::time::Duration::from_millis( 100 ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test permanent error (authentication)
  let auth_error = the_module::AnthropicError::Authentication( 
    the_module::AuthenticationError::new( "Invalid API key".to_string() ) 
  );
  let recovery_strategy = the_module::ErrorRecovery::analyze_error( &auth_error );
  
  match recovery_strategy
  {
    Ok( strategy ) =>
    {
      assert!( !strategy.should_retry() );
      assert!( strategy.requires_user_action() );
      assert!( strategy.suggested_action().contains( "API key" ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_user_actionable_error_messages_with_remediation()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real actionable error testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_error_aggregation_and_batch_error_handling()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real batch error handling testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_timeout_error_detection_and_classification()
{
  // Test different types of timeout errors
  // REMOVED: create_test_client() call - not needed for classification tests

  // Test connection timeout
  let connection_timeout = the_module::TimeoutError::new(
    the_module::TimeoutType::Connection,
    core::time::Duration::from_secs( 30 ),
    "Connection timeout after 30 seconds".to_string()
  );

  let classified_error = the_module::ErrorClassifier::classify_timeout( &connection_timeout );
  match classified_error
  {
    Ok( classified ) =>
    {
      assert_eq!( classified.timeout_type(), the_module::TimeoutType::Connection );
      assert!( classified.is_network_related() );
      assert!( classified.suggested_timeout_increase() > core::time::Duration::from_secs( 30 ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test read timeout
  let read_timeout = the_module::TimeoutError::new(
    the_module::TimeoutType::Read,
    core::time::Duration::from_secs( 60 ),
    "Read timeout after 60 seconds".to_string()
  );

  let classified_error = the_module::ErrorClassifier::classify_timeout( &read_timeout );
  match classified_error
  {
    Ok( classified ) =>
    {
      assert_eq!( classified.timeout_type(), the_module::TimeoutType::Read );
      assert!( classified.is_server_processing_related() );
      assert!( classified.supports_streaming_fallback() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_network_error_classification()
{
  // Test classification of different network error types
  
  // Test DNS resolution error
  let dns_error = the_module::NetworkError::new(
    the_module::NetworkErrorType::DnsResolution,
    "Failed to resolve api.anthropic.com".to_string(),
    Some( "NXDOMAIN".to_string() )
  );

  let classified = the_module::NetworkErrorClassifier::classify( &dns_error );
  match classified
  {
    Ok( classification ) =>
    {
      assert_eq!( classification.error_type(), the_module::NetworkErrorType::DnsResolution );
      assert!( classification.is_infrastructure_related() );
      assert!( classification.suggested_actions().contains( &"DNS".to_string() ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test SSL/TLS error
  let ssl_error = the_module::NetworkError::new(
    the_module::NetworkErrorType::SslHandshake,
    "SSL handshake failed".to_string(),
    Some( "certificate verify failed".to_string() )
  );

  let classified = the_module::NetworkErrorClassifier::classify( &ssl_error );
  match classified
  {
    Ok( classification ) =>
    {
      assert_eq!( classification.error_type(), the_module::NetworkErrorType::SslHandshake );
      assert!( classification.is_security_related() );
      assert!( classification.suggested_actions().contains( &"certificate".to_string() ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test connection refused error
  let connection_error = the_module::NetworkError::new(
    the_module::NetworkErrorType::ConnectionRefused,
    "Connection refused".to_string(),
    Some( "port 443".to_string() )
  );

  let classified = the_module::NetworkErrorClassifier::classify( &connection_error );
  match classified
  {
    Ok( classification ) =>
    {
      assert_eq!( classification.error_type(), the_module::NetworkErrorType::ConnectionRefused );
      assert!( classification.is_service_availability_related() );
      assert!( classification.supports_retry_with_backoff() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_rate_limiting_error_with_backoff_suggestions()
{
  // Test rate limiting error detection and backoff strategy suggestions
  // REMOVED: create_test_client() call - not needed for backoff tests

  let rate_limit_error = the_module::RateLimitError::new(
    "Too many requests".to_string(),
    Some( 60 ),
    "request_limit".to_string()
  );

  let backoff_strategy = the_module::BackoffCalculator::calculate_backoff( &rate_limit_error );
  match backoff_strategy
  {
    Ok( strategy ) =>
    {
      assert!( strategy.initial_delay() >= core::time::Duration::from_secs( 60 ) );
      assert_eq!( strategy.backoff_type(), the_module::BackoffType::Linear );
      assert!( strategy.max_retries() <= 5 );
      assert!( strategy.jitter_enabled() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test different rate limit types
  let token_rate_limit = the_module::RateLimitError::new(
    "Token limit exceeded".to_string(),
    Some( 300 ),
    "token_limit".to_string()
  );

  let backoff_strategy = the_module::BackoffCalculator::calculate_backoff( &token_rate_limit );
  match backoff_strategy
  {
    Ok( strategy ) =>
    {
      assert!( strategy.initial_delay() >= core::time::Duration::from_secs( 300 ) );
      assert!( strategy.suggested_batch_size_reduction().is_some() );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_authentication_error_with_credential_hints()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real credential hint testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_error_serialization_and_deserialization()
{
  // Test that errors can be properly serialized and deserialized
  let original_error = the_module::EnhancedAnthropicError::new(
    the_module::ErrorType::RateLimit,
    "Rate limit exceeded".to_string(),
    Some( the_module::ErrorContext::new(
      "create_message".to_string(),
      "req_123".to_string(),
      std::collections::HashMap::from([
        ( "model".to_string(), "claude-sonnet-4-5-20250929".to_string() ),
        ( "tokens".to_string(), "1000".to_string() ),
      ])
    ))
  );

  // Test serialization
  let serialized = the_module::ErrorSerializer::serialize( &original_error );
  match serialized
  {
    Ok( json_string ) =>
    {
      assert!( json_string.contains( "Rate limit exceeded" ) );
      assert!( json_string.contains( "req_123" ) );
      
      // Test deserialization
      let deserialized = the_module::ErrorSerializer::deserialize( &json_string );
      match deserialized
      {
        Ok( error ) =>
        {
          assert_eq!( error.error_type(), the_module::ErrorType::RateLimit );
          assert_eq!( error.message(), "Rate limit exceeded" );
          assert_eq!( error.context().unwrap().request_id(), "req_123" );
        },
        Err( _err ) =>
        {
          // Expected to fail until enhanced error handling is implemented
        }
      }
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_error_logging_and_monitoring_integration()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real error logging testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_error_correlation_and_request_tracking()
{
  // REMOVED: This test used fake API keys and is not needed
  // Real error correlation testing is covered by integration tests using from_workspace()
  // Test functionality is covered by real integration tests
}

#[ tokio::test ]
async fn test_error_message_localization_support()
{
  // Test error message localization
  let error = the_module::AnthropicError::InvalidRequest(
    "Invalid model parameter".to_string()
  );

  // Test English localization (default)
  let localized_en = the_module::ErrorLocalizer::localize( &error, "en" );
  match localized_en
  {
    Ok( localized ) =>
    {
      assert!( localized.message().contains( "Invalid model parameter" ) );
      assert_eq!( localized.locale(), "en" );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test Spanish localization
  let spanish_localized = the_module::ErrorLocalizer::localize( &error, "es" );
  match spanish_localized
  {
    Ok( localized ) =>
    {
      assert!( localized.message().contains( "parámetro del modelo" ) );
      assert_eq!( localized.locale(), "es" );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }

  // Test French localization
  let localized_fr = the_module::ErrorLocalizer::localize( &error, "fr" );
  match localized_fr
  {
    Ok( localized ) =>
    {
      assert!( localized.message().contains( "paramètre de modèle" ) );
      assert_eq!( localized.locale(), "fr" );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

#[ tokio::test ]
async fn test_custom_error_types_and_chaining()
{
  // Test custom error types and error chaining
  
  // Create custom domain-specific error
  let domain_error = the_module::CustomError::new(
    "ModelConfigurationError".to_string(),
    "Model temperature out of range".to_string(),
    the_module::ErrorSeverity::Medium
  );

  // Chain with underlying API error
  let api_error = the_module::AnthropicError::InvalidRequest(
    "Temperature must be between 0.0 and 1.0".to_string()
  );

  let chained_error = the_module::ErrorChain::new( domain_error )
    .caused_by( api_error )
    .with_context( "temperature validation" );

  match chained_error.build()
  {
    Ok( error ) =>
    {
      assert_eq!( error.chain_length(), 2 );
      assert!( error.root_cause().contains( "Temperature must be between" ) );
      assert!( error.immediate_cause().contains( "Model temperature out of range" ) );
      assert!( error.has_context() );
      assert_eq!( error.context(), "temperature validation" );

      // Test error chain traversal
      let chain_iterator = error.chain_iterator();
      let errors : Vec< _ > = chain_iterator.collect();
      assert_eq!( errors.len(), 2 );
      assert!( errors[ 0 ].contains( "Model temperature out of range" ) );
      assert!( errors[ 1 ].contains( "Temperature must be between" ) );
    },
    Err( _err ) =>
    {
      // Expected to fail until enhanced error handling is implemented
    }
  }
}

// Helper functions for tests

// REMOVED: create_test_client function - all mockup tests have been eliminated
// Real testing is covered by integration tests using Client::from_workspace()

// REMOVED: create_invalid_request function - no longer needed after removing mockup tests

// ============================================================================
// INTEGRATION TESTS - REAL API ERROR HANDLING
// ============================================================================

#[ tokio::test ]
#[ cfg( feature = "integration" ) ]
#[ ignore = "Requires workspace secrets file" ]
async fn integration_error_handling_network_timeout()
{
  let client = the_module::Client::from_workspace()
    .expect( "INTEGRATION: Must have valid API key for timeout testing" );

  // Test with extremely large request that might timeout
  let large_request = the_module::CreateMessageRequest
  {
    model : "claude-3-5-haiku-20241022".to_string(),
    max_tokens : 4000, // Large response
    messages : vec![ 
      the_module::Message::user( 
        "Write a very detailed analysis of quantum computing, machine learning, blockchain technology, and artificial intelligence. Include mathematical formulas, code examples, and comprehensive explanations of each topic. Make it as detailed as possible.".repeat( 20 )
      ) 
    ],
    system : Some( vec![ the_module::SystemContent::text( "You are a comprehensive technical expert. Provide extremely detailed responses." ) ] ),
    temperature : Some( 0.3 ),
    stream : None,
    tools : None,
    tool_choice : None,
  };

  let result = client.create_message( large_request ).await;
  
  // This should either succeed or fail with appropriate error handling
  match result
  {
    Ok( response ) => {
      assert!( !response.id.is_empty(), "Large request response must have ID" );
      assert!( response.usage.output_tokens > 0, "Must generate tokens" );
      println!( "✅ Large request succeeded : {} tokens", response.usage.output_tokens );
    },
    Err( error ) => {
      let error_str = error.to_string().to_lowercase();
      // Should be a meaningful error (timeout, rate limit, etc.)
      assert!( 
        error_str.contains( "timeout" ) || 
        error_str.contains( "rate" ) || 
        error_str.contains( "limit" ) ||
        error_str.contains( "request" ),
        "Large request error should be meaningful : {error}"
      );
      println!( "✅ Large request properly handled error : {error}" );
    }
  }
}

#[ tokio::test ]
#[ cfg( feature = "integration" ) ]
#[ ignore = "Requires workspace secrets file" ]
async fn integration_error_handling_invalid_parameters()
{
  // Skip test if API key is not available
  // Integration test requires valid API key - fail if not available
  let client = the_module::Client::from_workspace()
    .expect( "Integration test requires valid API key. Set ANTHROPIC_API_KEY environment variable or configure workspace secrets." );

  // Test with invalid temperature
  let invalid_temp_request = the_module::CreateMessageRequest
  {
    model : "claude-3-5-haiku-20241022".to_string(),
    max_tokens : 10,
    messages : vec![ the_module::Message::user( "Test".to_string() ) ],
    system : None,
    temperature : Some( 2.5 ), // Invalid temperature (>1.0)
    stream : None,
    tools : None,
    tool_choice : None,
  };

  let result = client.create_message( invalid_temp_request ).await;
  
  // Should return error for invalid temperature
  assert!( result.is_err(), "Invalid temperature should cause error" );
  let error = result.unwrap_err();
  let error_str = error.to_string().to_lowercase();
  assert!( 
    error_str.contains( "temperature" ) || 
    error_str.contains( "parameter" ) ||
    error_str.contains( "invalid" ),
    "Temperature error should mention the issue : {error}"
  );

  println!( "✅ Invalid parameter error handling integration test passed!" );
  println!( "   Invalid temperature properly rejected : {error}" );
}

#[ tokio::test ]
#[ cfg( feature = "integration" ) ]
async fn integration_error_handling_authentication_failures()
{
  // Test with invalid API key
  let invalid_secret = the_module::Secret::new( "sk-ant-invalid-key-12345".to_string() )
    .expect( "Invalid secret should construct" );
  let invalid_client = the_module::Client::new( invalid_secret );

  let request = the_module::CreateMessageRequest
  {
    model : "claude-3-5-haiku-20241022".to_string(),
    max_tokens : 10,
    messages : vec![ the_module::Message::user( "Test auth".to_string() ) ],
    system : None,
    temperature : None,
    stream : None,
    tools : None,
    tool_choice : None,
  };

  let result = invalid_client.create_message( request ).await;
  
  // Should fail with authentication error
  assert!( result.is_err(), "Invalid API key should cause authentication error" );
  let error = result.unwrap_err();
  let error_str = error.to_string().to_lowercase();
  assert!( 
    error_str.contains( "authentication" ) || 
    error_str.contains( "unauthorized" ) ||
    error_str.contains( "invalid" ) ||
    error_str.contains( "key" ),
    "Auth error should mention authentication issue : {error}"
  );

  println!( "✅ Authentication error handling integration test passed!" );
  println!( "   Invalid API key properly rejected : {error}" );
}

// ============================================================================
// REAL ERROR SCENARIO TESTS - TESTING ACTUAL IMPLEMENTATION
// ============================================================================

#[ cfg( feature = "streaming" ) ]
#[ tokio::test ]
async fn test_sse_parsing_errors_malformed_json()
{
  // Test parsing errors for SSE events with malformed JSON
  let malformed_message_start = r#"event : message_start
data : {"id": "msg_123", "type": INVALID_JSON}

"#;

  let result = the_module::parse_sse_events( malformed_message_start );
  assert!( result.is_ok(), "Should parse and filter out bad events" );
}

#[ cfg( feature = "streaming" ) ]
#[ tokio::test ]
async fn test_sse_parsing_unknown_event_type()
{
  // Test handling of unknown event types
  let unknown_event = r#"event : unknown_event_type
data : {"some": "data"}

"#;

  let result = the_module::parse_sse_events( unknown_event );
  // Should succeed and filter out unknown events
  assert!( result.is_ok() );
}

#[ cfg( feature = "streaming" ) ]
#[ tokio::test ]
async fn test_sse_parsing_content_block_delta_errors()
{
  // Test parsing error for content_block_delta with missing fields
  let incomplete_delta = r#"event : content_block_delta
data : {"index": 0}

"#;

  let result = the_module::parse_sse_events( incomplete_delta );
  // Should succeed but not include invalid event
  assert!( result.is_ok() );
}

#[ cfg( feature = "error-handling" ) ]
#[ test ]
fn test_error_classification_is_retryable()
{
  // Test is_retryable() for different error types

  // Retryable errors
  let rate_limit_err = the_module::AnthropicError::RateLimit(
    the_module::RateLimitError::new( "Rate limited".to_string(), Some( 60 ), "request".to_string() )
  );
  assert!( rate_limit_err.is_retryable(), "Rate limit errors should be retryable" );

  let internal_err = the_module::AnthropicError::Internal( "Server error".to_string() );
  assert!( internal_err.is_retryable(), "Internal errors should be retryable" );

  let stream_err = the_module::AnthropicError::Stream( "Stream interrupted".to_string() );
  assert!( stream_err.is_retryable(), "Stream errors should be retryable" );

  // Non-retryable errors
  let invalid_arg_err = the_module::AnthropicError::InvalidArgument( "Bad input".to_string() );
  assert!( !invalid_arg_err.is_retryable(), "Invalid argument errors should not be retryable" );

  let auth_err = the_module::AnthropicError::Authentication(
    the_module::AuthenticationError::new( "Bad key".to_string() )
  );
  assert!( !auth_err.is_retryable(), "Authentication errors should not be retryable" );

  let parsing_err = the_module::AnthropicError::Parsing( "Parse failed".to_string() );
  assert!( !parsing_err.is_retryable(), "Parsing errors should not be retryable" );
}

#[ cfg( feature = "error-handling" ) ]
#[ test ]
fn test_error_severity_classification()
{
  use the_module::ErrorSeverity;

  // Critical severity
  let auth_err = the_module::AnthropicError::Authentication(
    the_module::AuthenticationError::new( "Invalid key".to_string() )
  );
  assert_eq!( auth_err.severity(), ErrorSeverity::Critical, "Auth errors should be critical" );

  let missing_env_err = the_module::AnthropicError::MissingEnvironment( "No API key".to_string() );
  assert_eq!( missing_env_err.severity(), ErrorSeverity::Critical, "Missing env errors should be critical" );

  // High severity
  let invalid_req_err = the_module::AnthropicError::InvalidRequest( "Bad params".to_string() );
  assert_eq!( invalid_req_err.severity(), ErrorSeverity::High, "Invalid request errors should be high" );

  // Medium severity
  let rate_limit_err = the_module::AnthropicError::RateLimit(
    the_module::RateLimitError::new( "Rate limited".to_string(), Some( 60 ), "request".to_string() )
  );
  assert_eq!( rate_limit_err.severity(), ErrorSeverity::Medium, "Rate limit errors should be medium" );
}

#[ cfg( feature = "error-handling" ) ]
#[ test ]
fn test_error_display_formatting()
{
  // Test that error messages are properly formatted

  let parsing_err = the_module::AnthropicError::Parsing( "JSON parse failed".to_string() );
  let err_msg = format!( "{parsing_err}" );
  assert!( err_msg.contains( "Parsing error" ) && err_msg.contains( "JSON parse failed" ),
    "Parsing error should contain type and message : {err_msg}" );

  let internal_err = the_module::AnthropicError::Internal( "Internal failure".to_string() );
  let err_msg = format!( "{internal_err}" );
  assert!( err_msg.contains( "Internal error" ) && err_msg.contains( "Internal failure" ),
    "Internal error should contain type and message : {err_msg}" );

  let missing_env_err = the_module::AnthropicError::MissingEnvironment( "ANTHROPIC_API_KEY not set".to_string() );
  let err_msg = format!( "{missing_env_err}" );
  assert!( err_msg.contains( "Missing environment" ) && err_msg.contains( "ANTHROPIC_API_KEY" ),
    "Missing env error should contain type and variable : {err_msg}" );

  let file_err = the_module::AnthropicError::File( "File not found".to_string() );
  let err_msg = format!( "{file_err}" );
  assert!( err_msg.contains( "File error" ) && err_msg.contains( "File not found" ),
    "File error should contain type and message : {err_msg}" );

  let not_impl_err = the_module::AnthropicError::NotImplemented( "Feature X not implemented".to_string() );
  let err_msg = format!( "{not_impl_err}" );
  assert!( err_msg.contains( "Not implemented" ) && err_msg.contains( "Feature X" ),
    "NotImplemented error should contain type and feature : {err_msg}" );
}

#[ cfg( feature = "error-handling" ) ]
#[ test ]
fn test_error_recovery_suggestions()
{
  // Test that errors provide helpful recovery suggestions

  let missing_env_err = the_module::AnthropicError::MissingEnvironment(
    "ANTHROPIC_API_KEY not found".to_string()
  );
  let suggestions = missing_env_err.recovery_suggestions();
  assert!( !suggestions.is_empty(), "Missing env errors should have recovery suggestions" );
  assert!( suggestions.iter().any( | s | s.contains( "ANTHROPIC_API_KEY" ) || s.contains( "environment" ) ),
    "Suggestions should mention the environment variable" );

  let auth_err = the_module::AnthropicError::Authentication(
    the_module::AuthenticationError::new( "Invalid API key".to_string() )
  );
  let suggestions = auth_err.recovery_suggestions();
  assert!( !suggestions.is_empty(), "Auth errors should have recovery suggestions" );

  let rate_limit_err = the_module::AnthropicError::RateLimit(
    the_module::RateLimitError::new( "Rate limited".to_string(), Some( 60 ), "request".to_string() )
  );
  let suggestions = rate_limit_err.recovery_suggestions();
  assert!( !suggestions.is_empty(), "Rate limit errors should have recovery suggestions" );
}

#[ cfg( all( feature = "streaming", feature = "error-handling" ) ) ]
#[ tokio::test ]
async fn test_stream_event_validation()
{
  // Test validation of stream events

  // Valid message should pass validation
  let valid_message = the_module::StreamMessage::new(
    "msg_123",
    "message",
    "assistant",
    "claude-sonnet-4-5-20250929",
    the_module::Usage
    {
      input_tokens : 10,
      output_tokens : 50,
      cache_creation_input_tokens : None,
      cache_read_input_tokens : None,
    }
  );
  assert!( valid_message.validate().is_ok(), "Valid message should pass validation" );

  // Test text content block validation
  let text_block = the_module::StreamContentBlock::new_text( "Hello world" );
  assert!( text_block.validate().is_ok(), "Valid text block should pass validation" );

  // Test text delta validation
  let text_delta = the_module::StreamDelta::new_text( "Hello" );
  assert!( text_delta.validate().is_ok(), "Valid text delta should pass validation" );
}