seedkit 2.1.1

Generate realistic, constraint-safe seed data for PostgreSQL, MySQL, and SQLite
use clap::{Parser, Subcommand, ValueEnum};

#[derive(Parser, Debug)]
#[command(
    name = "seedkit",
    about = "Generate realistic, constraint-safe seed data for any database",
    version,
    after_help = "Examples:\n  seedkit generate --db postgres://localhost/myapp --rows 1000 --output seed.sql\n  seedkit generate --rows 100              # auto-detect DB from .env\n  seedkit introspect --db postgres://localhost/myapp\n  seedkit preview --db postgres://localhost/myapp\n  seedkit check --db postgres://localhost/myapp\n  seedkit graph --db postgres://localhost/myapp --format mermaid"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    pub verbose: bool,
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Generate seed data for a database
    Generate(GenerateArgs),

    /// Introspect a database schema and display analysis
    Introspect(IntrospectArgs),

    /// Preview sample generated data without inserting
    Preview(PreviewArgs),

    /// Check for schema drift against a lock file
    Check(CheckArgs),

    /// Visualize table dependency graph
    Graph(GraphArgs),

    /// Sample production distributions for realistic data generation
    Sample(SampleArgs),

    /// Delete the rows of the generated tables and reseed them in one transaction
    Reset(ResetArgs),
}

#[derive(Parser, Debug)]
pub struct GenerateArgs {
    #[command(flatten)]
    pub options: GenerationOptions,
    /// Output file path (.sql, .json, .csv), a directory for one CSV per table
    /// (with --format csv), or "direct" for DB insertion
    #[arg(short, long)]
    pub output: Option<String>,

    /// Output format (auto-detected from file extension if not specified)
    #[arg(long)]
    pub format: Option<OutputFormat>,

    /// Use PostgreSQL COPY format for output (faster for large datasets)
    #[arg(long)]
    pub copy: bool,
}

/// A DDL file to read instead of connecting to a database.
#[derive(clap::Args, Debug, Clone, Default)]
pub struct SchemaFile {
    /// Read the schema from a DDL file (CREATE TABLE statements or a
    /// pg_dump --schema-only file) instead of connecting to a database
    #[arg(long, value_name = "PATH", requires = "dialect")]
    pub schema_file: Option<std::path::PathBuf>,

    /// SQL dialect of --schema-file
    #[arg(long, value_enum, requires = "schema_file")]
    pub dialect: Option<Dialect>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Dialect {
    #[value(alias = "postgresql")]
    Postgres,
    Mysql,
    Sqlite,
}

#[derive(Parser, Debug)]
pub struct GenerationOptions {
    /// Database connection URL (postgres://, mysql://, sqlite://)
    /// Falls back to DATABASE_URL env var or .env file
    #[arg(long, env = "DATABASE_URL")]
    pub db: Option<String>,

    /// Number of rows to generate per table
    #[arg(long, conflicts_with = "from_lock")]
    pub rows: Option<usize>,

    /// Random seed for deterministic generation
    #[arg(long, conflicts_with = "from_lock")]
    pub seed: Option<u64>,

    /// Named relational fixture from [scenarios] in seedkit.toml
    #[arg(long, conflicts_with = "from_lock")]
    pub scenario: Option<String>,

    /// Per-table row count overrides (e.g., users=500,orders=2000)
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "TABLE=COUNT",
        value_parser = parse_table_rows_entry,
        conflicts_with = "from_lock"
    )]
    pub table_rows: Vec<(String, usize)>,

    /// Only generate data for these tables
    #[arg(long, value_delimiter = ',', conflicts_with = "from_lock")]
    pub include: Vec<String>,

    /// Exclude these tables from generation
    #[arg(long, value_delimiter = ',', conflicts_with = "from_lock")]
    pub exclude: Vec<String>,

    /// Schema name to introspect (default: public for Postgres)
    #[arg(long)]
    pub schema: Option<String>,

    #[command(flatten)]
    pub schema_file: SchemaFile,

    /// Use LLM for enhanced semantic classification
    #[arg(long)]
    pub ai: bool,

    /// LLM model to use with --ai
    #[arg(long)]
    pub model: Option<String>,

    /// Regenerate from a lock file
    #[arg(long)]
    pub from_lock: bool,

    /// Force regeneration even if schema has changed
    #[arg(long)]
    pub force: bool,

    /// Path to distribution profiles for production-like generation
    #[arg(long)]
    pub subset: Option<String>,

    /// Locale for names, places, companies, and phone numbers (e.g. de_DE, ja_JP)
    #[arg(long, value_name = "LOCALE", conflicts_with = "from_lock")]
    pub locale: Option<seedkit_core::generate::locale::Locale>,
}

#[derive(Parser, Debug)]
pub struct ResetArgs {
    #[command(flatten)]
    pub options: GenerationOptions,

    /// Skip the confirmation prompt
    #[arg(long, short = 'y')]
    pub yes: bool,
}

#[derive(Parser, Debug)]
pub struct IntrospectArgs {
    /// Database connection URL
    #[arg(long, env = "DATABASE_URL")]
    pub db: Option<String>,

    /// Schema name to introspect
    #[arg(long)]
    pub schema: Option<String>,

    #[command(flatten)]
    pub schema_file: SchemaFile,

    /// Output format
    #[arg(long, default_value = "table")]
    pub format: IntrospectFormat,
}

#[derive(Parser, Debug)]
pub struct PreviewArgs {
    #[command(flatten)]
    pub options: GenerationOptions,

    /// Maximum rows displayed per table (defaults to --rows or 5)
    #[arg(long)]
    pub limit: Option<usize>,
}

#[derive(Parser, Debug)]
pub struct CheckArgs {
    /// Database connection URL
    #[arg(long, env = "DATABASE_URL")]
    pub db: Option<String>,

    /// Schema name
    #[arg(long)]
    pub schema: Option<String>,

    #[command(flatten)]
    pub schema_file: SchemaFile,

    /// Output format for drift report
    #[arg(long, default_value = "text")]
    pub format: CheckFormat,
}

#[derive(Parser, Debug)]
pub struct GraphArgs {
    /// Database connection URL
    #[arg(long, env = "DATABASE_URL")]
    pub db: Option<String>,

    /// Schema name
    #[arg(long)]
    pub schema: Option<String>,

    #[command(flatten)]
    pub schema_file: SchemaFile,

    /// Output format for the dependency graph
    #[arg(long, default_value = "mermaid")]
    pub format: GraphFormat,
}

#[derive(Parser, Debug)]
pub struct SampleArgs {
    /// Database connection URL (read-only replica recommended)
    #[arg(long, env = "DATABASE_URL")]
    pub db: Option<String>,

    /// Schema name to introspect
    #[arg(long)]
    pub schema: Option<String>,

    /// Output path for distribution profiles
    #[arg(short, long)]
    pub output: Option<String>,

    /// Only sample these tables
    #[arg(long, value_delimiter = ',')]
    pub tables: Vec<String>,

    /// Record source labels for this text column (repeatable, table.column)
    #[arg(long, value_name = "TABLE.COLUMN", value_parser = parse_sample_column)]
    pub allow_text: Vec<(String, String)>,

    /// Maximum distinct values per categorical column
    #[arg(long, default_value = "50")]
    pub categorical_limit: usize,

    /// Minimum row count for a table to be sampled
    #[arg(long, default_value = "10")]
    pub min_rows: u64,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum OutputFormat {
    Sql,
    Json,
    Csv,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum IntrospectFormat {
    Table,
    Json,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum CheckFormat {
    Text,
    Json,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum GraphFormat {
    Mermaid,
    Dot,
}

fn parse_table_rows_entry(value: &str) -> Result<(String, usize), String> {
    value
        .split_once('=')
        .filter(|(table, _)| !table.is_empty())
        .and_then(|(table, count)| Some((table.to_owned(), count.parse().ok()?)))
        .ok_or_else(|| "expected TABLE=COUNT, e.g. users=500".to_owned())
}

fn parse_sample_column(value: &str) -> Result<(String, String), String> {
    let (table, column) = value
        .split_once('.')
        .filter(|(t, c)| !t.is_empty() && !c.is_empty())
        .ok_or("expected table.column")?;
    Ok((table.to_owned(), column.to_owned()))
}

impl GenerateArgs {
    /// The output directory when `--output` names one (an existing directory
    /// or a path ending in a separator). Each table then gets its own CSV.
    pub fn csv_directory(&self) -> Option<&std::path::Path> {
        let path = self.output.as_deref().filter(|p| *p != "direct")?;
        let is_dir = path.ends_with('/')
            || path.ends_with(std::path::MAIN_SEPARATOR)
            || std::path::Path::new(path).is_dir();
        is_dir.then(|| std::path::Path::new(path))
    }

    /// Determine output format from file extension or explicit format flag.
    pub fn output_format(&self) -> OutputFormat {
        if let Some(ref fmt) = self.format {
            return fmt.clone();
        }
        if let Some(ref path) = self.output {
            if path.ends_with(".json") {
                return OutputFormat::Json;
            } else if path.ends_with(".csv") {
                return OutputFormat::Csv;
            }
        }
        OutputFormat::Sql
    }
}

impl GenerationOptions {
    /// Table row overrides like "users=500,orders=2000", validated by clap.
    /// Returns a BTreeMap for deterministic lock file serialization.
    pub fn parse_table_rows(&self) -> std::collections::BTreeMap<String, usize> {
        self.table_rows.iter().cloned().collect()
    }
}