use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::Result;
use clap::{Parser, Subcommand};

mod overlay;
mod registry;
mod render;
mod sync;

#[derive(Parser)]
#[command(
    name = "xtask",
    about = "Rustelo workspace meta-tools (deps sync, integrity checks)"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Sync [workspace.dependencies] from registry/Cargo.toml into a Cargo.toml.
    SyncDeps(SyncDepsArgs),
}

#[derive(Parser)]
pub struct SyncDepsArgs {
    /// Verify only — exit non-zero if any target Cargo.toml differs from the rendered registry.
    #[arg(long)]
    pub check: bool,

    /// Target Cargo.toml directory. Defaults to the rustelo workspace root.
    /// For implementations, point this at the impl workspace dir (e.g. ../jpl-website).
    /// Mutually exclusive with --all.
    #[arg(long)]
    pub target: Option<PathBuf>,

    /// Path to the rustelo workspace root (where registry/Cargo.toml lives).
    /// Used to compute relative path rebasing for impl targets.
    #[arg(long, default_value = ".")]
    pub rustelo_root: PathBuf,

    /// Explicit path to an overlay file. Default: `{target}/rustelo-deps-overlay.toml`
    /// (auto-detected; absent = no overlay). Cannot be combined with --all
    /// (each impl uses its own auto-detected overlay).
    #[arg(long)]
    pub overlay: Option<PathBuf>,

    /// Sync the rustelo workspace plus every implementation listed in
    /// `registry/sync.toml` `[impls.known]`. Drift in any target sets a
    /// non-zero exit status; all targets are visited regardless of intermediate
    /// drift (no fail-fast). Mutually exclusive with --target and --overlay.
    #[arg(long)]
    pub all: bool,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let result: Result<ExitCode> = match cli.cmd {
        Cmd::SyncDeps(args) => sync::run(args),
    };
    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("xtask: {e:#}");
            ExitCode::from(2)
        }
    }
}
