seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! # LLM API Client
//!
//! Sends schema analysis requests to Claude or OpenAI and returns the raw
//! response text. Supports auto-detection of the API key from environment
//! variables and optional model overrides via `--model`.
//!
//! Responses are cached to `~/.seedkit/cache/`, keyed by provider, model,
//! and schema hash, so repeated runs against the same schema avoid redundant
//! API calls.

use sha2::{Digest, Sha256};
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use super::truncate;
use crate::error::{Result, SeedKitError};

/// Supported LLM providers.
#[derive(Debug, Clone)]
pub enum LlmProvider {
    Claude { api_key: String, model: String },
    OpenAI { api_key: String, model: String },
    Gemini { api_key: String, model: String },
}

/// API keys found in the environment, one per provider.
#[derive(Clone, Default)]
pub struct ApiKeys {
    pub anthropic: Option<String>,
    pub openai: Option<String>,
    pub gemini: Option<String>,
}

impl ApiKeys {
    /// `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and `GEMINI_API_KEY` (or
    /// `GOOGLE_API_KEY`, which Google's SDKs also read).
    pub fn from_env() -> Self {
        let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
        Self {
            anthropic: var("ANTHROPIC_API_KEY"),
            openai: var("OPENAI_API_KEY"),
            gemini: var("GEMINI_API_KEY").or_else(|| var("GOOGLE_API_KEY")),
        }
    }
}

/// Claude model used when `--model` is not given.
pub const DEFAULT_CLAUDE_MODEL: &str = "claude-opus-5-5";

/// OpenAI model used when `--model` is not given. OpenAI's deprecations page
/// names it as the replacement for gpt-4o, gpt-4o-mini, and gpt-4.1.
pub const DEFAULT_OPENAI_MODEL: &str = "gpt-6-luna";

/// Gemini model used when `--model` is not given. Google recommends it for
/// new projects, and it answered every column in testing.
pub const DEFAULT_GEMINI_MODEL: &str = "gemini-3.5-flash-lite";

/// Model families that enforce `output_config.format` JSON schemas and accept
/// `effort`. Other models get a plain request and follow the prompt's format.
const STRUCTURED_OUTPUT_PREFIXES: &[&str] = &[
    "claude-fable-5",
    "claude-mythos-5",
    "claude-opus-5",
    "claude-opus-4-8",
    "claude-sonnet-5",
    "claude-haiku-5",
];

/// Models that retry a safety decline on another model server-side.
const SERVER_FALLBACK_MODELS: &[&str] = &[
    "claude-fable-5-2",
    "claude-fable-5-1",
    "claude-opus-5-5",
    "claude-opus-5",
    "claude-sonnet-5-5",
];
const SERVER_FALLBACK_BETA: &str = "server-side-fallback-2026-07-01";

/// Changes whenever the prompt or response format changes, so cached
/// responses in the old format are not reused.
const CACHE_FORMAT: &str = "classifications-v3";

impl LlmProvider {
    /// Pick a provider from the API keys in the environment.
    ///
    /// Without `--model`, Anthropic is preferred, then OpenAI, then Gemini,
    /// each with its default model.
    pub fn from_env(model_override: Option<&str>) -> Result<Self> {
        Self::from_keys(ApiKeys::from_env(), model_override)
    }

    /// A `--model` name selects its provider (`claude-*`, an OpenAI name, or
    /// `gemini-*`); the matching key must be set.
    fn from_keys(keys: ApiKeys, model_override: Option<&str>) -> Result<Self> {
        let missing = |variable: &str, model: &str| SeedKitError::LlmError {
            message: format!("--model {model} needs {variable} to be set."),
        };
        match model_override {
            Some(model) if is_openai_model(model) => {
                let api_key = keys
                    .openai
                    .ok_or_else(|| missing("OPENAI_API_KEY", model))?;
                return Ok(LlmProvider::OpenAI {
                    api_key,
                    model: model.to_owned(),
                });
            }
            Some(model) if model.starts_with("claude") => {
                let api_key = keys
                    .anthropic
                    .ok_or_else(|| missing("ANTHROPIC_API_KEY", model))?;
                return Ok(LlmProvider::Claude {
                    api_key,
                    model: model.to_owned(),
                });
            }
            Some(model) if model.starts_with("gemini") => {
                let api_key = keys
                    .gemini
                    .ok_or_else(|| missing("GEMINI_API_KEY", model))?;
                return Ok(LlmProvider::Gemini {
                    api_key,
                    model: model.to_owned(),
                });
            }
            _ => {}
        }

        let model = |default: &str| model_override.unwrap_or(default).to_string();
        if let Some(api_key) = keys.anthropic {
            return Ok(LlmProvider::Claude {
                api_key,
                model: model(DEFAULT_CLAUDE_MODEL),
            });
        }
        if let Some(api_key) = keys.openai {
            return Ok(LlmProvider::OpenAI {
                api_key,
                model: model(DEFAULT_OPENAI_MODEL),
            });
        }
        if let Some(api_key) = keys.gemini {
            return Ok(LlmProvider::Gemini {
                api_key,
                model: model(DEFAULT_GEMINI_MODEL),
            });
        }

        Err(SeedKitError::LlmError {
            message: "No LLM API key found. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or \
                      GEMINI_API_KEY."
                .to_string(),
        })
    }

    /// The model that answers classification requests.
    pub fn model(&self) -> &str {
        match self {
            LlmProvider::Claude { model, .. }
            | LlmProvider::OpenAI { model, .. }
            | LlmProvider::Gemini { model, .. } => model,
        }
    }

    /// Cache file key for this provider, model, response format, and request
    /// input (the schema hash and the columns being classified).
    pub fn cache_key(&self, input: &str) -> String {
        let (provider, model) = match self {
            LlmProvider::Claude { model, .. } => ("anthropic", model),
            LlmProvider::OpenAI { model, .. } => ("openai", model),
            LlmProvider::Gemini { model, .. } => ("google", model),
        };
        let mut hash = Sha256::new();
        for part in [CACHE_FORMAT, provider, model.as_str(), input] {
            hash.update((part.len() as u64).to_le_bytes());
            hash.update(part.as_bytes());
        }
        format!("{:x}", hash.finalize())
    }

    /// Send a prompt to the LLM and return the raw response text.
    pub async fn classify(&self, prompt: &str) -> Result<String> {
        match self {
            LlmProvider::Claude { api_key, model } => call_claude(api_key, model, prompt).await,
            LlmProvider::OpenAI { api_key, model } => call_openai(api_key, model, prompt).await,
            LlmProvider::Gemini { api_key, model } => call_gemini(api_key, model, prompt).await,
        }
    }
}

/// Maximum time to wait for an LLM API response before aborting. A large
/// schema can take several minutes to classify at `max_tokens` 16000; this
/// matches the official SDKs' default timeout.
const API_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);

/// Build an HTTP client with a strict timeout so requests never hang
/// indefinitely on flaky networks or partial API outages.
fn build_http_client() -> reqwest::Client {
    reqwest::Client::builder()
        .timeout(API_TIMEOUT)
        .build()
        .unwrap_or_else(|_| reqwest::Client::new())
}

/// Retries after a rate limit, overload, or server error, as the official
/// SDKs do.
const MAX_RETRIES: u32 = 2;
const MAX_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(60);

/// How long to wait before retrying a failed request, or `None` to give up.
/// A `Retry-After` header in seconds takes precedence over the 1 s, 2 s backoff.
fn retry_delay(
    status: reqwest::StatusCode,
    retry_after: Option<&str>,
    attempt: u32,
) -> Option<std::time::Duration> {
    let transient = matches!(status.as_u16(), 408 | 409 | 429) || status.is_server_error();
    if !transient || attempt >= MAX_RETRIES {
        return None;
    }
    let delay = retry_after
        .and_then(|seconds| seconds.trim().parse::<u64>().ok())
        .map(std::time::Duration::from_secs)
        .unwrap_or(std::time::Duration::from_secs(1 << attempt));
    Some(delay.min(MAX_RETRY_DELAY))
}

/// Send a JSON request and return the body of a successful response,
/// retrying connection failures and transient HTTP errors.
async fn send(request: reqwest::RequestBuilder, api: &str) -> Result<String> {
    let mut attempt = 0;
    loop {
        let this_try = request
            .try_clone()
            .expect("a JSON request body can be cloned");
        let response = match this_try.send().await {
            Ok(response) => response,
            Err(err) if err.is_connect() && attempt < MAX_RETRIES => {
                tokio::time::sleep(std::time::Duration::from_secs(1 << attempt)).await;
                attempt += 1;
                continue;
            }
            Err(err) => {
                return Err(SeedKitError::LlmError {
                    message: format!("Failed to call {api} API: {err}"),
                })
            }
        };
        let status = response.status();
        let retry_after = response
            .headers()
            .get(reqwest::header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let text = response.text().await.map_err(|e| SeedKitError::LlmError {
            message: format!("Failed to read {api} API response: {e}"),
        })?;
        if status.is_success() {
            return Ok(text);
        }
        match retry_delay(status, retry_after.as_deref(), attempt) {
            Some(delay) => {
                tracing::debug!("{api} API returned {status}; retrying in {delay:?}");
                tokio::time::sleep(delay).await;
                attempt += 1;
            }
            None => {
                return Err(SeedKitError::LlmError {
                    message: format!("{api} API returned {status}: {}", truncate(&text, 500)),
                })
            }
        }
    }
}

/// Call the Anthropic Messages API.
async fn call_claude(api_key: &str, model: &str, prompt: &str) -> Result<String> {
    let client = build_http_client();
    let (body, beta) = claude_request(model, prompt);

    let mut request = client
        .post("https://api.anthropic.com/v1/messages")
        .header("x-api-key", api_key)
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json");
    if let Some(beta) = beta {
        request = request.header("anthropic-beta", beta);
    }
    let response_text = send(request.json(&body), "Claude").await?;
    claude_text(&response_text)
}

/// Request body for one classification call, plus the beta header it needs.
///
/// Current models reject assistant prefill, so the response format comes
/// from a JSON schema (`output_config.format`) where the model supports it,
/// and from the prompt otherwise.
fn claude_request(model: &str, prompt: &str) -> (serde_json::Value, Option<&'static str>) {
    let mut body = serde_json::json!({
        "model": model,
        "max_tokens": 16000,
        "messages": [{"role": "user", "content": prompt}],
    });
    if STRUCTURED_OUTPUT_PREFIXES
        .iter()
        .any(|prefix| model.starts_with(prefix))
    {
        // Measured on Claude Opus 5.5: at low effort some answers stopped
        // after one column; medium answered every column, without thinking
        // tokens on this task.
        body["output_config"] = serde_json::json!({
            "effort": "medium",
            "format": {
                "type": "json_schema",
                "schema": super::prompt::classification_schema(true),
            },
        });
    }
    if SERVER_FALLBACK_MODELS.contains(&model) {
        body["fallbacks"] = serde_json::json!("default");
        return (body, Some(SERVER_FALLBACK_BETA));
    }
    (body, None)
}

/// The text of a Messages API response, after checking why it stopped.
/// Thinking and fallback blocks carry no classifications and are skipped.
fn claude_text(response_text: &str) -> Result<String> {
    let parsed: serde_json::Value =
        serde_json::from_str(response_text).map_err(|e| SeedKitError::LlmError {
            message: format!("Failed to parse Claude API response JSON: {}", e),
        })?;

    match parsed["stop_reason"].as_str() {
        Some("refusal") => {
            let details = &parsed["stop_details"];
            return Err(SeedKitError::LlmError {
                message: format!(
                    "Claude declined to classify the schema ({}): {}",
                    details["category"].as_str().unwrap_or("no category"),
                    details["explanation"].as_str().unwrap_or("no explanation"),
                ),
            });
        }
        Some("max_tokens") => {
            return Err(SeedKitError::LlmError {
                message: "Claude's classification stopped at max_tokens before the JSON was \
                          complete; the schema may be too large for one request"
                    .to_string(),
            });
        }
        _ => {}
    }

    let text: String = parsed["content"]
        .as_array()
        .into_iter()
        .flatten()
        .filter(|block| block["type"] == "text")
        .filter_map(|block| block["text"].as_str())
        .collect();
    if text.is_empty() {
        return Err(SeedKitError::LlmError {
            message: "Claude API response has no text content".to_string(),
        });
    }
    Ok(text)
}

/// Call the OpenAI Chat Completions API.
async fn call_openai(api_key: &str, model: &str, prompt: &str) -> Result<String> {
    let client = build_http_client();
    let body = openai_request(model, prompt);

    let request = client
        .post("https://api.openai.com/v1/chat/completions")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("content-type", "application/json")
        .json(&body);
    let response_text = send(request, "OpenAI").await?;
    openai_text(&response_text)
}

/// OpenAI model names: `gpt-*`, `chatgpt-*`, and the o-series (`o3`, `o4-mini`).
fn is_openai_model(model: &str) -> bool {
    model.starts_with("gpt-")
        || model.starts_with("chatgpt-")
        || model
            .strip_prefix('o')
            .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
}

/// GPT-5 and later and the o-series reason, and only they accept `reasoning_effort`.
fn is_openai_reasoning_model(model: &str) -> bool {
    let generation = model
        .strip_prefix("gpt-")
        .and_then(|rest| rest.split(|c: char| !c.is_ascii_digit()).next())
        .and_then(|major| major.parse::<u32>().ok());
    generation.is_some_and(|major| major >= 5) || (is_openai_model(model) && model.starts_with('o'))
}

/// Chat Completions request with the response held to the classification schema.
fn openai_request(model: &str, prompt: &str) -> serde_json::Value {
    let mut body = serde_json::json!({
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        // Reasoning models reject max_tokens; every chat model accepts this.
        "max_completion_tokens": 16000,
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "column_classifications",
                "strict": true,
                "schema": super::prompt::classification_schema(true),
            },
        },
    });
    if is_openai_reasoning_model(model) {
        // Low effort answered every column when measured on gpt-6-luna.
        body["reasoning_effort"] = serde_json::json!("low");
    }
    body
}

/// The content of a Chat Completions response, after checking why it stopped.
fn openai_text(response_text: &str) -> Result<String> {
    let parsed: serde_json::Value =
        serde_json::from_str(response_text).map_err(|e| SeedKitError::LlmError {
            message: format!("Failed to parse OpenAI API response JSON: {}", e),
        })?;
    let choice = &parsed["choices"][0];
    if let Some(refusal) = choice["message"]["refusal"].as_str() {
        return Err(SeedKitError::LlmError {
            message: format!("OpenAI declined to classify the schema: {refusal}"),
        });
    }
    if choice["finish_reason"] == "length" {
        return Err(SeedKitError::LlmError {
            message: "OpenAI's classification stopped at max_completion_tokens before the JSON \
                      was complete; the schema may be too large for one request"
                .to_string(),
        });
    }
    choice["message"]["content"]
        .as_str()
        .map(str::to_owned)
        .ok_or_else(|| SeedKitError::LlmError {
            message: "OpenAI API response missing choices[0].message.content".to_string(),
        })
}

/// Call the Gemini `generateContent` API.
async fn call_gemini(api_key: &str, model: &str, prompt: &str) -> Result<String> {
    let request = build_http_client()
        .post(gemini_url(model)?)
        .header("x-goog-api-key", api_key)
        .header("content-type", "application/json")
        .json(&gemini_request(model, prompt));
    gemini_text(&send(request, "Gemini").await?)
}

/// The `generateContent` URL for a model. The name becomes part of the path,
/// so only plain model names are accepted.
fn gemini_url(model: &str) -> Result<String> {
    let plain = !model.is_empty()
        && model
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'));
    if !plain {
        return Err(SeedKitError::LlmError {
            message: format!("Invalid Gemini model name: {model:?}"),
        });
    }
    Ok(format!(
        "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
    ))
}

/// The major version in a Gemini model name (`gemini-3.5-flash-lite` -> 3).
fn gemini_generation(model: &str) -> Option<u32> {
    model
        .strip_prefix("gemini-")?
        .split(|c: char| !c.is_ascii_digit())
        .next()?
        .parse()
        .ok()
}

/// `generateContent` request with the response held to the classification
/// schema. Gemini rejects the semantic-type enum ("too much branching for
/// serving"), so types are checked after parsing instead.
fn gemini_request(model: &str, prompt: &str) -> serde_json::Value {
    let mut config = serde_json::json!({
        "responseMimeType": "application/json",
        "responseJsonSchema": super::prompt::classification_schema(false),
        // Thinking tokens count toward this limit on Gemini.
        "maxOutputTokens": 16000,
    });
    // thinkingLevel is an error on models before Gemini 3.
    if gemini_generation(model).is_some_and(|major| major >= 3) {
        config["thinkingConfig"] = serde_json::json!({"thinkingLevel": "low"});
    }
    serde_json::json!({
        "contents": [{"role": "user", "parts": [{"text": prompt}]}],
        "generationConfig": config,
    })
}

/// The answer text of a `generateContent` response, after checking for a
/// blocked prompt and why generation stopped. Thought parts are skipped.
fn gemini_text(response_text: &str) -> Result<String> {
    let parsed: serde_json::Value =
        serde_json::from_str(response_text).map_err(|e| SeedKitError::LlmError {
            message: format!("Failed to parse Gemini API response JSON: {}", e),
        })?;
    if let Some(reason) = parsed["promptFeedback"]["blockReason"].as_str() {
        return Err(SeedKitError::LlmError {
            message: format!("Gemini blocked the classification request ({reason})"),
        });
    }
    let candidate = &parsed["candidates"][0];
    match candidate["finishReason"].as_str() {
        None | Some("STOP") => {}
        Some("MAX_TOKENS") => {
            return Err(SeedKitError::LlmError {
                message: "Gemini's classification stopped at maxOutputTokens before the JSON \
                          was complete; the schema may be too large for one request"
                    .to_string(),
            })
        }
        Some(reason) => {
            return Err(SeedKitError::LlmError {
                message: format!("Gemini stopped without an answer ({reason})"),
            })
        }
    }
    let text: String = candidate["content"]["parts"]
        .as_array()
        .into_iter()
        .flatten()
        .filter(|part| part["thought"] != true)
        .filter_map(|part| part["text"].as_str())
        .collect();
    if text.is_empty() {
        return Err(SeedKitError::LlmError {
            message: "Gemini API response has no text content".to_string(),
        });
    }
    Ok(text)
}

// ---------------------------------------------------------------------------
// Response caching
// ---------------------------------------------------------------------------

/// Return the cache directory path: `~/.seedkit/cache/`.
fn cache_dir() -> Option<PathBuf> {
    dirs_free().map(|home| home.join(".seedkit").join("cache"))
}

/// Platform-independent home directory lookup (no extra crate needed).
fn dirs_free() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

/// Try to load a cached LLM response for the given schema hash.
pub fn load_cached_response(schema_hash: &str) -> Option<String> {
    load_cached_response_in(&cache_dir()?, schema_hash)
}

fn load_cached_response_in(dir: &Path, schema_hash: &str) -> Option<String> {
    std::fs::read_to_string(dir.join(format!("{schema_hash}.json"))).ok()
}

/// Save an LLM response to the cache, keyed by schema hash.
///
/// Uses atomic write (temp file → `sync_all` → rename) to avoid corruption
/// if the process is interrupted mid-write.
pub fn save_cached_response(schema_hash: &str, response: &str) {
    if let Some(dir) = cache_dir() {
        if let Err(err) = save_cached_response_in(&dir, schema_hash, response) {
            tracing::debug!("Failed to cache LLM response: {err}");
        }
    }
}

fn save_cached_response_in(dir: &Path, schema_hash: &str, response: &str) -> io::Result<()> {
    std::fs::create_dir_all(dir)?;
    let mut file = tempfile::NamedTempFile::new_in(dir)?;
    file.write_all(response.as_bytes())?;
    file.as_file().sync_all()?;
    file.persist(dir.join(format!("{schema_hash}.json")))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn keys(anthropic: Option<&str>, openai: Option<&str>, gemini: Option<&str>) -> ApiKeys {
        ApiKeys {
            anthropic: anthropic.map(Into::into),
            openai: openai.map(Into::into),
            gemini: gemini.map(Into::into),
        }
    }

    fn gemini(model: &str) -> serde_json::Value {
        gemini_request(model, "classify these columns")
    }

    #[test]
    fn default_gemini_model_is_current() {
        match LlmProvider::from_keys(keys(None, None, Some("g")), None).unwrap() {
            LlmProvider::Gemini { model, .. } => assert_eq!(model, "gemini-3.5-flash-lite"),
            other => panic!("expected Gemini, got {other:?}"),
        }
        // Without a --model, Anthropic and then OpenAI keys take precedence.
        let all = LlmProvider::from_keys(keys(Some("a"), Some("o"), Some("g")), None).unwrap();
        assert!(matches!(all, LlmProvider::Claude { .. }));
        let two = LlmProvider::from_keys(keys(None, Some("o"), Some("g")), None).unwrap();
        assert!(matches!(two, LlmProvider::OpenAI { .. }));
    }

    #[test]
    fn gemini_model_names_select_gemini() {
        let all = keys(Some("a"), Some("o"), Some("g"));
        let chosen = LlmProvider::from_keys(all, Some("gemini-4-hydrogen")).unwrap();
        assert_eq!(chosen.model(), "gemini-4-hydrogen");
        assert!(matches!(chosen, LlmProvider::Gemini { .. }));
        let err =
            LlmProvider::from_keys(keys(Some("a"), None, None), Some("gemini-3.5-flash-lite"))
                .unwrap_err();
        assert!(err.to_string().contains("GEMINI_API_KEY"), "{err}");
    }

    #[test]
    fn gemini_requests_use_a_json_schema_without_the_type_enum() {
        let body = gemini(DEFAULT_GEMINI_MODEL);
        assert_eq!(body["contents"][0]["role"], "user");
        assert_eq!(
            body["contents"][0]["parts"][0]["text"],
            "classify these columns"
        );
        let config = &body["generationConfig"];
        assert_eq!(config["responseMimeType"], "application/json");
        assert_eq!(config["maxOutputTokens"], 16000);
        let item = &config["responseJsonSchema"]["properties"]["classifications"]["items"];
        // Gemini rejects the 87-value enum as "too much branching for serving".
        assert!(item["properties"]["semantic_type"].get("enum").is_none());
        assert_eq!(item["properties"]["semantic_type"]["type"], "string");
        assert_eq!(config["thinkingConfig"]["thinkingLevel"], "low");
        assert_eq!(
            gemini("gemini-4-hydrogen")["generationConfig"]["thinkingConfig"]["thinkingLevel"],
            "low"
        );
        // thinkingLevel is an error before Gemini 3, and aliases name no version.
        for model in ["gemini-2.5-flash-lite", "gemini-flash-latest"] {
            assert!(
                gemini(model)["generationConfig"]
                    .get("thinkingConfig")
                    .is_none(),
                "{model}"
            );
        }
    }

    #[test]
    fn gemini_text_skips_thoughts_and_reports_blocks_and_stops() {
        let ok = r#"{"candidates": [{"finishReason": "STOP", "content": {"role": "model", "parts": [
            {"text": "planning", "thought": true},
            {"text": "{\"classifications\": []}"}]}}]}"#;
        assert_eq!(gemini_text(ok).unwrap(), r#"{"classifications": []}"#);

        let blocked = r#"{"promptFeedback": {"blockReason": "PROHIBITED_CONTENT"}}"#;
        let err = gemini_text(blocked).unwrap_err().to_string();
        assert!(err.contains("PROHIBITED_CONTENT"), "{err}");

        let cut = r#"{"candidates": [{"finishReason": "MAX_TOKENS", "content": {"parts": [{"text": "{\"cl"}]}}]}"#;
        let err = gemini_text(cut).unwrap_err().to_string();
        assert!(err.contains("maxOutputTokens"), "{err}");

        let unsafe_stop =
            r#"{"candidates": [{"finishReason": "SAFETY", "content": {"parts": []}}]}"#;
        let err = gemini_text(unsafe_stop).unwrap_err().to_string();
        assert!(err.contains("SAFETY"), "{err}");
    }

    #[test]
    fn gemini_urls_accept_only_plain_model_names() {
        assert_eq!(
            gemini_url("gemini-3.5-flash-lite").unwrap(),
            "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent"
        );
        for model in ["gemini-x/../tunedModels/y", "gemini x", "gemini?key=1"] {
            assert!(gemini_url(model).is_err(), "{model}");
        }
    }

    #[test]
    fn transient_failures_are_retried_with_backoff() {
        use reqwest::StatusCode;
        let seconds = |status, retry_after, attempt| {
            retry_delay(StatusCode::from_u16(status).unwrap(), retry_after, attempt)
                .map(|d| d.as_secs())
        };
        assert_eq!(seconds(429, None, 0), Some(1));
        assert_eq!(seconds(503, None, 1), Some(2));
        assert_eq!(seconds(529, Some("7"), 0), Some(7));
        assert_eq!(
            seconds(429, Some("3600"), 0),
            Some(MAX_RETRY_DELAY.as_secs())
        );
        assert_eq!(seconds(500, None, MAX_RETRIES), None);
        for status in [400, 401, 403, 404] {
            assert_eq!(seconds(status, None, 0), None, "{status}");
        }
    }

    #[test]
    fn cache_keys_separate_gemini() {
        let claude = LlmProvider::from_keys(keys(Some("a"), None, None), None).unwrap();
        let gemini = LlmProvider::from_keys(keys(None, None, Some("g")), None).unwrap();
        assert_ne!(claude.cache_key("schema"), gemini.cache_key("schema"));
    }

    #[test]
    fn test_no_keys() {
        let err = LlmProvider::from_keys(keys(None, None, None), None).unwrap_err();
        assert!(err.to_string().contains("GEMINI_API_KEY"), "{err}");
    }

    #[test]
    fn test_anthropic_key_takes_precedence() {
        let provider =
            LlmProvider::from_keys(keys(Some("test-key-123"), Some("other"), None), None).unwrap();
        match provider {
            LlmProvider::Claude { api_key, model } => {
                assert_eq!(api_key, "test-key-123");
                assert!(model.contains("claude"));
            }
            _ => panic!("Expected Claude provider"),
        }
    }

    #[test]
    fn test_model_override() {
        let provider = LlmProvider::from_keys(
            keys(Some("test-key"), None, None),
            Some("claude-sonnet-5-5"),
        )
        .unwrap();
        match provider {
            LlmProvider::Claude { model, .. } => {
                assert_eq!(model, "claude-sonnet-5-5");
            }
            _ => panic!("Expected Claude provider"),
        }
    }

    #[test]
    fn test_cache_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let hash = "test_cache_hash_12345";
        let response = r#"[{"table":"users","column":"email","semantic_type":"Email"}]"#;

        save_cached_response_in(dir.path(), hash, response).unwrap();
        let loaded = load_cached_response_in(dir.path(), hash);
        assert_eq!(loaded.as_deref(), Some(response));
    }

    #[test]
    fn test_cache_miss() {
        let dir = tempfile::tempdir().unwrap();
        let result = load_cached_response_in(dir.path(), "nonexistent_hash_99999");
        assert!(result.is_none());
    }

    #[test]
    fn test_truncate_short() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_long() {
        assert_eq!(truncate("hello world", 5), "hello");
    }

    #[test]
    fn truncate_keeps_whole_characters() {
        // Error bodies can be localized; byte 501 falls inside a 2-byte "é".
        let body = "é".repeat(300);
        assert_eq!(truncate(&body, 501), "é".repeat(250));
    }

    #[test]
    fn concurrent_writers_publish_one_complete_response() {
        let dir = tempfile::tempdir().unwrap();
        let barrier = std::sync::Barrier::new(4);
        let responses = ["a", "b", "c", "d"].map(|s| s.repeat(16_384));
        std::thread::scope(|scope| {
            for response in &responses {
                scope.spawn(|| {
                    barrier.wait();
                    save_cached_response_in(dir.path(), "shared", response).unwrap();
                });
            }
        });
        let published = load_cached_response_in(dir.path(), "shared").unwrap();
        assert!(responses.contains(&published));
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[test]
    fn test_atomic_cache_overwrites_existing() {
        let dir = tempfile::tempdir().unwrap();
        let hash = "test_atomic_cache_overwrite_42";

        save_cached_response_in(dir.path(), hash, "first version").unwrap();
        save_cached_response_in(dir.path(), hash, "second version").unwrap();

        let loaded = load_cached_response_in(dir.path(), hash);
        assert_eq!(loaded.as_deref(), Some("second version"));
    }

    fn claude(model: &str) -> (serde_json::Value, Option<&'static str>) {
        claude_request(model, "classify these columns")
    }

    #[test]
    fn default_claude_model_is_current() {
        // claude-sonnet-4-20250514 was retired on 2026-06-15.
        match LlmProvider::from_keys(keys(Some("key"), None, None), None).unwrap() {
            LlmProvider::Claude { model, .. } => assert_eq!(model, "claude-opus-5-5"),
            other => panic!("expected Claude, got {other:?}"),
        }
    }

    #[test]
    fn claude_requests_use_structured_output_instead_of_prefill() {
        let (body, beta) = claude(DEFAULT_CLAUDE_MODEL);
        // Current models reject a trailing assistant message (prefill) with a 400.
        assert_eq!(body["messages"].as_array().unwrap().len(), 1);
        assert_eq!(body["messages"][0]["role"], "user");
        assert_eq!(body["max_tokens"], 16000);
        let output = &body["output_config"];
        assert_eq!(output["effort"], "medium");
        assert_eq!(output["format"]["type"], "json_schema");
        let item = &output["format"]["schema"]["properties"]["classifications"]["items"];
        let labels = item["properties"]["semantic_type"]["enum"]
            .as_array()
            .unwrap();
        assert!(labels.contains(&"Email".into()) && labels.contains(&"Unknown".into()));
        assert_eq!(body["fallbacks"], "default");
        assert_eq!(beta, Some("server-side-fallback-2026-07-01"));
    }

    #[test]
    fn claude_requests_match_each_model_family() {
        // Haiku 5.5 has no server-side fallback; a fallbacks list would 400.
        let (body, beta) = claude("claude-haiku-5-5");
        assert_eq!(body["output_config"]["format"]["type"], "json_schema");
        assert!(body.get("fallbacks").is_none() && beta.is_none());
        // Older models get a plain request: no effort, schema, or fallbacks.
        for model in ["claude-sonnet-4-6", "claude-haiku-4-5"] {
            let (body, beta) = claude(model);
            assert!(body.get("output_config").is_none(), "{model}");
            assert!(body.get("fallbacks").is_none() && beta.is_none(), "{model}");
            assert_eq!(body["messages"].as_array().unwrap().len(), 1, "{model}");
        }
    }

    #[test]
    fn claude_text_skips_thinking_and_fallback_blocks() {
        let response = r#"{"stop_reason": "end_turn", "content": [
            {"type": "thinking", "thinking": "", "signature": "x"},
            {"type": "fallback", "from": {"model": "claude-opus-5-5"}, "to": {"model": "claude-opus-5"}},
            {"type": "text", "text": "{\"classifications\": []}"}
        ]}"#;
        assert_eq!(claude_text(response).unwrap(), r#"{"classifications": []}"#);
    }

    #[test]
    fn claude_text_reports_refusals_and_truncation() {
        let refusal = r#"{"stop_reason": "refusal", "content": [],
            "stop_details": {"type": "refusal", "category": "cyber", "explanation": "declined"}}"#;
        let err = claude_text(refusal).unwrap_err().to_string();
        assert!(err.contains("declined") && err.contains("cyber"), "{err}");

        let cut =
            r#"{"stop_reason": "max_tokens", "content": [{"type": "text", "text": "{\"classif"}]}"#;
        let err = claude_text(cut).unwrap_err().to_string();
        assert!(err.contains("max_tokens"), "{err}");
    }

    #[test]
    fn cache_keys_separate_providers_and_models() {
        let opus = LlmProvider::from_keys(keys(Some("k"), None, None), None).unwrap();
        let sonnet =
            LlmProvider::from_keys(keys(Some("k"), None, None), Some("claude-sonnet-5-5")).unwrap();
        let openai = LlmProvider::from_keys(keys(None, Some("k"), None), None).unwrap();
        let keys = [&opus, &sonnet, &openai].map(|p| p.cache_key("schema"));
        assert_eq!(
            keys.iter().collect::<std::collections::HashSet<_>>().len(),
            3
        );
        assert_eq!(opus.cache_key("schema"), keys[0]);
        assert_ne!(opus.cache_key("other"), keys[0]);
        assert!(keys
            .iter()
            .all(|k| k.len() == 64 && k.bytes().all(|b| b.is_ascii_hexdigit())));
    }

    fn openai(model: &str) -> serde_json::Value {
        openai_request(model, "classify these columns")
    }

    #[test]
    fn default_openai_model_replaces_gpt_4o() {
        // OpenAI's deprecations page names gpt-6-luna as gpt-4o's replacement.
        match LlmProvider::from_keys(keys(None, Some("key"), None), None).unwrap() {
            LlmProvider::OpenAI { model, .. } => assert_eq!(model, "gpt-6-luna"),
            other => panic!("expected OpenAI, got {other:?}"),
        }
    }

    #[test]
    fn openai_requests_use_a_strict_schema_and_completion_token_limit() {
        let body = openai(DEFAULT_OPENAI_MODEL);
        // gpt-6-luna rejects max_tokens; max_completion_tokens works on every model.
        assert!(body.get("max_tokens").is_none());
        assert_eq!(body["max_completion_tokens"], 16000);
        assert_eq!(body["reasoning_effort"], "low");
        let format = &body["response_format"];
        assert_eq!(format["type"], "json_schema");
        assert_eq!(format["json_schema"]["strict"], true);
        assert_eq!(
            format["json_schema"]["schema"]["required"],
            serde_json::json!(["classifications"])
        );
        // Models without reasoning reject reasoning_effort.
        for model in ["gpt-4o", "gpt-4.1-mini"] {
            let pinned = openai(model);
            assert!(pinned.get("reasoning_effort").is_none(), "{model}");
            assert_eq!(pinned["max_completion_tokens"], 16000, "{model}");
        }
    }

    #[test]
    fn openai_text_reports_refusals_and_truncation() {
        let ok = r#"{"choices": [{"finish_reason": "stop",
            "message": {"content": "{\"classifications\": []}", "refusal": null}}]}"#;
        assert_eq!(openai_text(ok).unwrap(), r#"{"classifications": []}"#);
        let refused = r#"{"choices": [{"finish_reason": "stop",
            "message": {"content": null, "refusal": "I can't help with that."}}]}"#;
        let err = openai_text(refused).unwrap_err().to_string();
        assert!(err.contains("can't help"), "{err}");
        let cut = r#"{"choices": [{"finish_reason": "length",
            "message": {"content": "{\"classif", "refusal": null}}]}"#;
        let err = openai_text(cut).unwrap_err().to_string();
        assert!(err.contains("max_completion_tokens"), "{err}");
    }

    #[test]
    fn model_name_selects_the_provider() {
        let both = |model| LlmProvider::from_keys(keys(Some("a"), Some("o"), None), model);
        assert!(matches!(
            both(Some("gpt-6-luna")),
            Ok(LlmProvider::OpenAI { .. })
        ));
        assert!(matches!(both(Some("o3")), Ok(LlmProvider::OpenAI { .. })));
        assert!(matches!(
            both(Some("claude-sonnet-5-5")),
            Ok(LlmProvider::Claude { .. })
        ));
        assert!(matches!(both(None), Ok(LlmProvider::Claude { .. })));
        // A model whose provider has no key is an error, not a silent switch.
        let err =
            LlmProvider::from_keys(keys(Some("a"), None, None), Some("gpt-6-luna")).unwrap_err();
        assert!(err.to_string().contains("OPENAI_API_KEY"), "{err}");
        let err = LlmProvider::from_keys(keys(None, Some("o"), None), Some("claude-opus-5-5"))
            .unwrap_err();
        assert!(err.to_string().contains("ANTHROPIC_API_KEY"), "{err}");
    }

    #[test]
    fn test_http_client_has_timeout() {
        // Verify the client builder produces a client with timeout configured.
        // We can't directly inspect reqwest's internals, but we can verify
        // build_http_client() doesn't panic.
        let client = build_http_client();
        // If we got here, the client was built successfully with timeout
        assert!(std::mem::size_of_val(&client) > 0);
    }
}