use std::path::PathBuf;

use rho_core::{RhoResult, copy_dir_recursive, has_flag, remove_dir_if_exists};

fn usage() -> ! {
    eprintln!(
        "usage: rho publish <owner> <dataset-uuid> [--source-root <path>] [--target-root <path>] [--force]"
    );
    std::process::exit(2);
}

fn option_value(args: &[String], flag: &str, default: &str) -> PathBuf {
    rho_core::arg_value(args, flag)
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(default))
}

pub fn run(args: &[String]) -> RhoResult<()> {
    if args.len() < 2 || args.iter().any(|arg| arg == "--help" || arg == "-h") {
        usage();
    }
    let owner = &args[0];
    let dataset_uuid = &args[1];
    let source_root = option_value(&args[2..], "--source-root", "users");
    let target_root = option_value(&args[2..], "--target-root", "shared/datasets");
    let source = source_root
        .join(owner)
        .join("datasets/share")
        .join(dataset_uuid);
    let target = target_root.join(dataset_uuid);

    if !source.is_dir() {
        return Err(format!("share bundle not found: {}", source.display()).into());
    }
    if target.exists() {
        if has_flag(args, "--force") {
            remove_dir_if_exists(&target)?;
        } else {
            return Err(format!(
                "target already exists: {} (rerun with --force)",
                target.display()
            )
            .into());
        }
    }
    copy_dir_recursive(&source, &target)?;
    println!("published dataset");
    println!("owner: {owner}");
    println!("uuid: {dataset_uuid}");
    println!("source: {}", source.display());
    println!("target: {}", target.display());
    Ok(())
}
