use anyhow::Result;
use clap::Parser;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct Config {
    pub src_dir: PathBuf,
    pub out_dir: PathBuf,
    pub snippets_dir: PathBuf,
    pub content_dir: PathBuf,
    pub static_dir: PathBuf,
    pub port: u16,
    pub watch: bool,
    pub verbose: bool,
}

#[derive(Parser, Debug, Clone)]
#[command(
    name = "snippets",
    version = env!("SNIPPETS_BUILD_VERSION"),
    about = "Build HTML templates with TOML-powered snippets",
    disable_help_subcommand = true,
    arg_required_else_help = true,
    after_help = "Examples:\n  snippets ./site ./dist --watch\n  snippets ./site ./dist --snippets-dir ./site/partials --verbose"
)]
struct Args {
    /// Source templates root (contains .htmlt files)
    pub src_dir: PathBuf,
    /// Output directory for rendered .html files
    pub out_dir: PathBuf,

    /// Snippets directory (default: <src_dir>/snippets)
    #[arg(long)]
    pub snippets_dir: Option<PathBuf>,
    /// Content directory (default: <src_dir>/content)
    #[arg(long)]
    pub content_dir: Option<PathBuf>,
    /// Static assets directory (default: <src_dir>/static)
    #[arg(long)]
    pub static_dir: Option<PathBuf>,

    /// Port to serve on in --watch mode
    #[arg(long, short = 'p', default_value_t = 8080)]
    pub port: u16,
    /// Watch for changes and rebuild incrementally
    #[arg(long)]
    pub watch: bool,
    /// Verbose logging (sets RUST_LOG=debug)
    #[arg(long, short = 'v')]
    pub verbose: bool,
}

pub fn parse_args() -> Result<Config> {
    let args = Args::parse();

    // Defaults relative to src_dir
    let snippets_dir = args
        .snippets_dir
        .clone()
        .unwrap_or_else(|| args.src_dir.join("snippets"));
    let content_dir = args
        .content_dir
        .clone()
        .unwrap_or_else(|| args.src_dir.join("content"));
    let static_dir = args
        .static_dir
        .clone()
        .unwrap_or_else(|| args.src_dir.join("static"));

    Ok(Config {
        src_dir: args.src_dir,
        out_dir: args.out_dir,
        snippets_dir,
        content_dir,
        static_dir,
        port: args.port,
        watch: args.watch,
        verbose: args.verbose,
    })
}
