seedkit 2.1.1

Generate realistic, constraint-safe seed data for PostgreSQL, MySQL, and SQLite
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
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

use anyhow::{bail, Context, Result};
use indicatif::{ProgressBar, ProgressStyle};

use seedkit_core::check::compute_schema_hash;
use seedkit_core::classify::rules::classify_schema;
use seedkit_core::classify::semantic::SemanticType;
use seedkit_core::config::ColumnConfig;
use seedkit_core::generate::engine;
use seedkit_core::generate::plan::{filter_insertion_order, GenerationPlan};
use seedkit_core::graph::cycle::break_cycles;
use seedkit_core::graph::dag::DependencyGraph;
use seedkit_core::graph::topo::topological_sort;
use seedkit_core::llm;
use seedkit_core::llm::classify::ClassificationTarget;
use seedkit_core::lock;
use seedkit_core::lock::types::{LockConfig, LockFile};
use seedkit_core::output;
use seedkit_core::schema::types::{DatabaseSchema, DatabaseType};

use crate::args::{GenerateArgs, GenerationOptions, OutputFormat};

pub(super) struct Prepared {
    pub plan: GenerationPlan,
    pub schema: DatabaseSchema,
    db_url: String,
    original_schema: Option<DatabaseSchema>,
    parent_locks: Vec<seedkit_core::generate::existing::LockedParent>,
    lock_config: LockConfig,
    scenario: Option<seedkit_core::generate::scenario::NamedScenario>,
}

impl Prepared {
    pub(super) fn db_url(&self) -> &str {
        &self.db_url
    }

    /// The schema as introspected, before `[[existing_parents]]` detached
    /// any relationships.
    pub(super) fn introspected(&self) -> &DatabaseSchema {
        self.original_schema.as_ref().unwrap_or(&self.schema)
    }

    /// Write `seedkit.lock` so teammates can reproduce this run.
    pub(super) fn write_lock(self) -> Result<()> {
        let lock_schema = self.original_schema.unwrap_or(self.schema);
        let mut lock_file = LockFile::new(
            compute_schema_hash(&lock_schema),
            self.plan.seed,
            self.plan.base_time,
            self.lock_config,
            lock_schema,
        );
        lock_file.generator_version = self.plan.generator_version;
        lock_file.existing_parents = self.parent_locks;
        lock_file.scenario = self.scenario;
        lock::write_lock_file(&lock_file, Path::new(lock::LOCK_FILE_NAME))?;
        eprintln!("Lock file written to {}", lock::LOCK_FILE_NAME);
        Ok(())
    }
}

pub(super) async fn prepare(args: &GenerationOptions) -> Result<Prepared> {
    // Load optional seedkit.toml config
    let config = seedkit_core::config::read_config(Path::new("."))?;

    // Phase 1: Introspect
    let pb = ProgressBar::new_spinner();
    pb.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.cyan} [{prefix}] {msg}")
            .unwrap(),
    );
    pb.set_prefix("1/4");
    pb.set_message("Introspecting schema...");
    pb.enable_steady_tick(std::time::Duration::from_millis(100));

    let (db_url, mut schema) = super::database::introspect(
        args.db.as_deref(),
        args.schema.as_deref(),
        config.as_ref(),
        &args.schema_file,
    )
    .await?;

    pb.finish_with_message(format!(
        "Introspecting schema... ✓ {} tables, {} foreign keys",
        schema.table_count(),
        schema.foreign_key_count()
    ));

    // A mistyped table would silently produce an empty or unchanged dataset.
    let flag_tables = [
        ("--include", args.include.iter().collect::<Vec<_>>()),
        ("--exclude", args.exclude.iter().collect()),
        (
            "--table-rows",
            args.table_rows.iter().map(|(t, _)| t).collect(),
        ),
    ];
    for (flag, names) in flag_tables {
        if let Some(unknown) = names.into_iter().find(|t| !schema.tables.contains_key(*t)) {
            bail!(
                "Unknown table '{unknown}' in {flag}. Tables in this schema: {}",
                table_list(&schema)
            );
        }
    }
    if let (Some(cfg), false) = (&config, args.from_lock) {
        for warning in config_warnings(cfg, &schema) {
            eprintln!("Warning: {warning}");
        }
    }

    // If --from-lock, load the lock file and validate schema hash
    let lock_path = Path::new(lock::LOCK_FILE_NAME);
    let restored_lock = if args.from_lock {
        if !lock_path.exists() {
            bail!(
                "No {} found in current directory. Run `seedkit generate` first to create one.",
                lock::LOCK_FILE_NAME
            );
        }
        let lf = lock::read_lock_file(lock_path)?;

        let current_hash = compute_schema_hash(&schema);
        if current_hash != lf.schema_hash && !args.force {
            bail!(
                "Schema has changed since {} was created.\n\
                 Lock hash: {:.16}\n\
                 Current:   {:.16}\n\
                 \n\
                 Run with --force to regenerate, or delete {} and run fresh.",
                lock::LOCK_FILE_NAME,
                lf.schema_hash,
                current_hash,
                lock::LOCK_FILE_NAME,
            );
        }
        Some(lf)
    } else {
        None
    };

    // Phase 2: Analyze dependencies
    let pb2 = ProgressBar::new_spinner();
    pb2.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.cyan} [{prefix}] {msg}")
            .unwrap(),
    );
    pb2.set_prefix("2/4");
    pb2.set_message("Analyzing dependencies...");
    pb2.enable_steady_tick(std::time::Duration::from_millis(100));

    let relationships = match &restored_lock {
        Some(lf) => lf
            .existing_parents
            .iter()
            .map(|p| p.relationship.clone())
            .collect(),
        None => config
            .as_ref()
            .map(|c| c.existing_parents.clone())
            .unwrap_or_default(),
    };
    let original_schema = (!relationships.is_empty()).then(|| schema.clone());
    if args.schema_file.schema_file.is_some() && !relationships.is_empty() {
        return Err(super::database::needs_database(
            "[[existing_parents]] reads parent keys from the database and",
        ));
    }
    let external = seedkit_core::generate::existing::detach(&mut schema, &relationships)?;
    let mut dep_graph = DependencyGraph::from_schema(&schema);
    let cycle_break_hints: Vec<String> = match restored_lock
        .as_ref()
        .and_then(|lf| lf.config.break_cycle_at.clone())
    {
        Some(recorded) => recorded,
        None => config
            .as_ref()
            .map(|c| c.graph.break_cycle_at.clone())
            .unwrap_or_default(),
    };
    let deferred = break_cycles(&mut dep_graph, &cycle_break_hints)?;
    let insertion_order = topological_sort(&dep_graph)?;

    pb2.finish_with_message(format!(
        "Analyzing dependencies... ✓ {} circular dependencies resolved",
        deferred.len()
    ));

    // Classify columns (rule-based)
    let introspected = original_schema.as_ref().unwrap_or(&schema);
    let rule_classifications = classify_schema(introspected);

    // Optionally enhance with LLM classification (--ai flag)
    let use_ai = args.ai
        || (restored_lock.is_none()
            && config.as_ref().and_then(|c| c.generate.ai).unwrap_or(false));
    let (classifications, ai_cache) = if use_ai {
        enhance_with_llm(&rule_classifications, introspected, args.model.as_deref()).await?
    } else if let Some(ref lf) = restored_lock {
        // Restore cached AI classifications from lock file
        restore_ai_from_lock(&rule_classifications, lf)
    } else {
        (rule_classifications, None)
    };

    // Build generation plan — use lock file values when restoring
    let (seed, row_count, table_row_overrides, base_time) = if let Some(ref lf) = restored_lock {
        let overrides = lf.config.table_row_overrides.clone();
        let bt = lf
            .parse_base_time()
            .context("Invalid base_time in seedkit.lock")?;
        (lf.seed, lf.config.default_row_count, overrides, Some(bt))
    } else {
        let seed = args.seed.unwrap_or_else(|| {
            // Check seedkit.toml for a fixed seed
            if let Some(ref cfg) = config {
                if let Some(s) = cfg.generate.seed {
                    return s;
                }
            }
            use std::time::{SystemTime, UNIX_EPOCH};
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
        });

        // Merge table row overrides: seedkit.toml as base, CLI --table-rows on top
        let mut overrides = config
            .as_ref()
            .map(|c| c.table_row_overrides())
            .unwrap_or_default();
        // CLI flags override config file
        for (k, v) in args.parse_table_rows() {
            overrides.insert(k, v);
        }

        // Row count: CLI --rows takes priority, then seedkit.toml, then default (100)
        let rows = args
            .rows
            .or_else(|| config.as_ref().and_then(|c| c.generate.rows))
            .unwrap_or(100);

        (seed, rows, overrides, None)
    };

    // Apply --include / --exclude table filtering.
    // When restoring from lock, use the lock's include/exclude lists.
    let (include, exclude) = if let Some(ref lf) = restored_lock {
        (
            lf.config.include_tables.clone(),
            lf.config.exclude_tables.clone(),
        )
    } else {
        (
            if args.include.is_empty() {
                config
                    .as_ref()
                    .and_then(|c| c.generate.include.clone())
                    .unwrap_or_default()
            } else {
                args.include.clone()
            },
            if args.exclude.is_empty() {
                config
                    .as_ref()
                    .and_then(|c| c.generate.exclude.clone())
                    .unwrap_or_default()
            } else {
                args.exclude.clone()
            },
        )
    };
    let filtered_order =
        filter_insertion_order(&insertion_order.tables, &schema, &include, &exclude);

    let column_overrides = match &restored_lock {
        Some(lf) => lf
            .config
            .column_overrides
            .iter()
            .flatten()
            .map(|(name, saved)| (name.clone(), ColumnConfig::from(saved)))
            .collect(),
        None => config
            .as_ref()
            .map(|c| c.columns.clone())
            .unwrap_or_default(),
    };

    let scenario = if let Some(lf) = &restored_lock {
        lf.scenario.clone()
    } else if let Some(name) = &args.scenario {
        let definition = config
            .as_ref()
            .and_then(|c| c.scenarios.get(name))
            .with_context(|| format!("Unknown scenario '{name}' in seedkit.toml"))?;
        Some(seedkit_core::generate::scenario::NamedScenario {
            name: name.clone(),
            definition: definition.clone(),
        })
    } else {
        None
    };

    let locked_subset = restored_lock
        .as_ref()
        .and_then(|lf| lf.config.subset.as_ref());
    let subset_path = args
        .subset
        .as_deref()
        .map(Path::new)
        .or_else(|| locked_subset.map(|source| source.path.as_path()));
    let (dist_profiles, subset) = if let Some(path) = subset_path {
        let (profiles, sha256) = seedkit_core::sample::load_profiles_with_hash(path)
            .with_context(|| format!("Loading distribution profile {}", path.display()))?;
        if locked_subset.is_some_and(|source| source.sha256 != sha256) {
            bail!("Distribution profile {} differs from seedkit.lock. Restore the recorded file or generate a new lock with --subset.", path.display());
        }
        eprintln!(
            "Loaded {} distribution profiles from {}",
            profiles.len(),
            path.display()
        );
        let source = seedkit_core::sample::ProfileSource {
            path: profile_lock_path(path)?,
            sha256,
        };
        (Some(profiles), Some(source))
    } else {
        (None, None)
    };

    let mut plan = GenerationPlan::build(
        &schema,
        &classifications,
        &filtered_order,
        deferred,
        row_count,
        &table_row_overrides,
        seed,
        base_time,
        &column_overrides,
        dist_profiles.as_deref(),
    );
    if let Some(lf) = &restored_lock {
        plan.generator_version = lf.generator_version;
    }
    plan.locale = match &restored_lock {
        Some(lf) => lf.config.locale.unwrap_or_default(),
        None => args
            .locale
            .or_else(|| config.as_ref().and_then(|c| c.generate.locale))
            .unwrap_or_default(),
    };

    if let Some(selected) = &scenario {
        selected
            .definition
            .apply(&mut plan, introspected)
            .with_context(|| format!("Invalid scenario '{}'", selected.name))?;
    }
    let parent_locks =
        seedkit_core::generate::existing::load(&mut plan, introspected, &external, &db_url).await?;
    if let Some(lf) = &restored_lock {
        if parent_locks != lf.existing_parents && !args.force {
            bail!("Existing parent keys have changed since seedkit.lock was written. Run with --force to use the current keys.");
        }
    }

    let lock_config = LockConfig {
        subset,
        default_row_count: row_count,
        table_row_overrides,
        ai_enabled: use_ai
            || restored_lock
                .as_ref()
                .is_some_and(|lf| lf.config.ai_enabled),
        include_tables: include,
        exclude_tables: exclude,
        break_cycle_at: Some(cycle_break_hints),
        locale: (plan.locale != Default::default()).then_some(plan.locale),
        ai_classifications: ai_cache,
        column_overrides: if column_overrides.is_empty() {
            None
        } else {
            Some(
                column_overrides
                    .iter()
                    .filter_map(|(k, cfg)| {
                        seedkit_core::lock::types::ColumnOverrideLock::capture(cfg)
                            .map(|saved| (k.clone(), saved))
                    })
                    .collect(),
            )
        },
    };
    Ok(Prepared {
        plan,
        schema,
        db_url,
        original_schema,
        parent_locks,
        lock_config,
        scenario,
    })
}

fn table_list(schema: &DatabaseSchema) -> String {
    let mut names: Vec<&str> = schema.tables.keys().map(String::as_str).collect();
    names.sort_unstable();
    names.join(", ")
}

/// Config entries that name tables or columns missing from the schema. They
/// may belong to another environment, so they warn instead of failing.
fn config_warnings(
    config: &seedkit_core::config::SeedKitConfig,
    schema: &DatabaseSchema,
) -> Vec<String> {
    let missing = |table: &String| !schema.tables.contains_key(table);
    let generate = &config.generate;
    let listed = [
        ("include", generate.include.iter().flatten()),
        ("exclude", generate.exclude.iter().flatten()),
    ];
    let mut warnings: Vec<String> = listed
        .into_iter()
        .flat_map(|(key, names)| {
            names.filter(|t| missing(t)).map(move |t| {
                format!(
                    "seedkit.toml: [generate] {key} names table '{t}', which is not in this schema"
                )
            })
        })
        .collect();
    warnings.extend(
        config
            .tables
            .keys()
            .filter(|t| missing(t))
            .map(|t| format!("seedkit.toml: [tables.{t}] does not match a table in this schema")),
    );
    warnings.extend(config.validate_against_schema(schema));
    warnings
}

// The lock lives in the working directory. Keep relative inputs portable, including
// an absolute input that shares an ancestor with the project directory.
fn profile_lock_path(path: &Path) -> Result<std::path::PathBuf> {
    if path.is_absolute() {
        let dir = std::env::current_dir()?;
        for (levels, ancestor) in dir.ancestors().enumerate() {
            if let Ok(suffix) = path.strip_prefix(ancestor) {
                let mut relative = std::path::PathBuf::new();
                relative.extend(std::iter::repeat_n("..", levels));
                return Ok(relative.join(suffix));
            }
        }
    }
    Ok(path.to_owned())
}

pub async fn run(args: &GenerateArgs) -> Result<()> {
    if args.output.as_deref() == Some("direct") && args.options.schema_file.schema_file.is_some() {
        return Err(super::database::needs_database("--output direct"));
    }
    let csv_dir = args.csv_directory();
    if let Some(dir) = csv_dir {
        if !matches!(args.format, Some(OutputFormat::Csv)) {
            bail!(
                "--output {} is a directory. Add --format csv to write one CSV file per table.",
                dir.display()
            );
        }
    }
    let prepared = prepare(&args.options).await?;
    let (plan, schema, db_url) = (&prepared.plan, &prepared.schema, prepared.db_url());

    // Phase 3: Generate data
    let total_rows: usize = plan.table_plans.iter().map(|t| t.row_count).sum();
    let pb3 = ProgressBar::new(total_rows as u64);
    pb3.set_style(
        ProgressStyle::default_bar()
            .template(
                "{spinner:.cyan} [3/4] Generating data... {bar:40.cyan/dim} {pos}/{len} ({eta})",
            )
            .unwrap()
            .progress_chars("█▓░"),
    );

    let data = engine::execute_plan(
        plan,
        schema,
        Some(&|_table, current, _total| {
            pb3.set_position(current as u64);
        }),
    )?;

    pb3.finish_with_message(format!("Generating data... ✓ ({} rows)", total_rows));

    // Phase 4: Output
    let is_direct = args.output.as_deref() == Some("direct");
    if args.copy
        && (is_direct
            || schema.database_type != DatabaseType::PostgreSQL
            || !matches!(args.output_format(), OutputFormat::Sql))
    {
        eprintln!("Warning: --copy applies only to PostgreSQL SQL output; ignoring it");
    }

    if is_direct {
        // Direct database insertion
        let pb4 = ProgressBar::new(total_rows as u64);
        pb4.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.cyan} [4/4] Inserting into database... {bar:40.cyan/dim} {pos}/{len} ({eta})")
                .unwrap()
                .progress_chars("█▓░"),
        );

        output::direct::insert_direct_with_offset(
            &data,
            schema,
            db_url,
            plan.sequence_offset,
            Some(&|current, _total| {
                pb4.set_position(current as u64);
            }),
        )
        .await?;

        pb4.finish_with_message(format!(
            "Inserting into database... ✓ ({} rows)",
            total_rows
        ));
        eprintln!(
            "\n✓ Inserted {} rows across {} tables into {}",
            total_rows,
            data.tables.len(),
            schema.database_type,
        );
    } else {
        let pb4 = ProgressBar::new_spinner();
        pb4.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.cyan} [4/4] {msg}")
                .unwrap(),
        );
        pb4.set_prefix("4/4");

        match &args.output {
            Some(path) if csv_dir.is_some() => {
                pb4.set_message(format!("Writing to {}...", path));
                let files = output::csv::write_csv_dir(Path::new(path), &data)?;
                pb4.finish_with_message(format!("Writing to {}... ✓", path));
                eprintln!(
                    "\n✓ Generated {} rows across {} tables → {} files in {}",
                    total_rows,
                    data.tables.len(),
                    files.len(),
                    path
                );
            }
            Some(path) => {
                pb4.set_message(format!("Writing to {}...", path));
                let file = File::create(path)
                    .with_context(|| format!("Failed to create output file: {}", path))?;
                let mut writer = BufWriter::new(file);

                write_output(&mut writer, args, &data, schema)?;

                pb4.finish_with_message(format!("Writing to {}... ✓", path));
                eprintln!(
                    "\n✓ Generated {} rows across {} tables → {}",
                    total_rows,
                    data.tables.len(),
                    path
                );
            }
            None => {
                // Write to stdout
                pb4.set_message("Writing to stdout...");
                let stdout = std::io::stdout();
                let mut writer = BufWriter::new(stdout.lock());

                write_output(&mut writer, args, &data, schema)?;

                pb4.finish_with_message("Writing to stdout... ✓");
            }
        }
    }

    // Write lock file (always, so teammates can reproduce)
    prepared.write_lock()?;

    Ok(())
}

/// Enhance rule-based classifications with LLM analysis.
///
/// Sends the schema to the configured LLM provider, caches the response,
/// and merges the results (LLM overrides only for `Unknown` columns).
async fn enhance_with_llm(
    rule_classifications: &BTreeMap<(String, String), SemanticType>,
    schema: &DatabaseSchema,
    model_override: Option<&str>,
) -> Result<(
    BTreeMap<(String, String), SemanticType>,
    Option<BTreeMap<String, BTreeMap<String, SemanticType>>>,
)> {
    let provider = llm::client::LlmProvider::from_env(model_override)
        .context("--ai flag requires an LLM API key")?;

    // Ask only about the columns the rules could not place; the merge keeps
    // rule-based types for every other column.
    let targets: Vec<ClassificationTarget> = rule_classifications
        .iter()
        .filter(|(_, semantic)| **semantic == SemanticType::Unknown)
        .filter_map(|((table, column), _)| {
            let col = schema.tables.get(table)?.columns.get(column)?;
            (!col.is_generated).then(|| ClassificationTarget::new(table, column, &col.raw_type))
        })
        .collect();
    if targets.is_empty() {
        eprintln!("Every column already has a semantic type; skipping LLM classification");
        return Ok((rule_classifications.clone(), None));
    }
    let requested: String = targets
        .iter()
        .map(|t| format!("{}.{}\n", t.table, t.column))
        .collect();
    let cache_key = provider.cache_key(&format!("{}\n{requested}", compute_schema_hash(schema)));

    // Check cache first
    let response = if let Some(cached) = llm::client::load_cached_response(&cache_key) {
        eprintln!("Using cached LLM classification (schema unchanged)");
        cached
    } else {
        eprintln!(
            "Asking {} to classify {} columns...",
            provider.model(),
            targets.len()
        );
        let ddl = llm::prompt::schema_to_compact_ddl(schema);
        let provider = &provider;
        let resp = llm::classify::classify_columns(&ddl, &targets, |prompt| async move {
            provider.classify(&prompt).await
        })
        .await
        .context("LLM classification request failed")?;
        llm::client::save_cached_response(&cache_key, &resp);
        resp
    };

    let merged = llm::parse::merge_classifications(rule_classifications, &response);
    let cache = llm::parse::build_ai_classification_cache(rule_classifications, &merged);
    let ai_cache = if cache.is_empty() { None } else { Some(cache) };

    Ok((merged, ai_cache))
}

/// Restore AI classifications from a lock file into the classification map.
#[allow(clippy::type_complexity)]
fn restore_ai_from_lock(
    rule_classifications: &BTreeMap<(String, String), SemanticType>,
    lock_file: &LockFile,
) -> (
    BTreeMap<(String, String), SemanticType>,
    Option<BTreeMap<String, BTreeMap<String, SemanticType>>>,
) {
    let mut merged = rule_classifications.clone();

    if let Some(ref ai_cache) = lock_file.config.ai_classifications {
        for (table, columns) in ai_cache {
            for (column, semantic_type) in columns {
                let key = (table.clone(), column.clone());
                // Only apply AI classification if rule engine says Unknown
                if merged.get(&key).copied().unwrap_or(SemanticType::Unknown)
                    == SemanticType::Unknown
                {
                    merged.insert(key, *semantic_type);
                }
            }
        }
    }

    (merged, lock_file.config.ai_classifications.clone())
}

fn write_output<W: Write>(
    writer: &mut W,
    args: &GenerateArgs,
    data: &engine::GeneratedData,
    schema: &DatabaseSchema,
) -> seedkit_core::error::Result<()> {
    match args.output_format() {
        OutputFormat::Sql if args.copy && schema.database_type == DatabaseType::PostgreSQL => {
            output::sql::write_postgres_copy(writer, data, schema)
        }
        OutputFormat::Sql => output::sql::write_sql(writer, data, schema),
        OutputFormat::Json => output::json::write_json(writer, data),
        OutputFormat::Csv => output::csv::write_csv(writer, data),
    }
}

#[cfg(test)]
mod output_tests {
    use super::*;
    use clap::Parser;
    use seedkit_core::generate::value::Value;

    #[test]
    fn copy_to_stdout_emits_default_inserts_and_copy_blocks() {
        let args = GenerateArgs::parse_from(["seedkit", "--copy"]);
        let data = engine::GeneratedData {
            tables: [
                ("roles".into(), vec![Default::default()]),
                (
                    "members".into(),
                    vec![[("role_id".into(), Value::Int(1))].into_iter().collect()],
                ),
            ]
            .into_iter()
            .collect(),
            deferred_updates: vec![],
        };
        let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".into());
        let mut output = Vec::new();
        write_output(&mut output, &args, &data, &schema).unwrap();
        let sql = String::from_utf8(output).unwrap();
        assert!(sql.contains("INSERT INTO \"roles\" DEFAULT VALUES;"));
        assert!(sql.contains("COPY \"members\" (\"role_id\") FROM stdin;"));
    }
}