mod app;

use argh::FromArgs;
use patchpal::ui::{utils, workspace};
use std::{ffi::OsString, process::ExitCode};

#[derive(FromArgs)]
#[argh(description =
    "AI-assisted commit cherry-picking tool.\n\
    You must be in the target directory where you want to apply the commit."
)]
struct Args {
    /// path to the repository to cherry-pick from; defaults to the current directory
    #[argh(option, short = 'g')]
    git: Option<OsString>,
    /// proceed also with non-clean cherry-picks; a human MUST always review the result for
    /// correctness
    #[argh(switch, short = 'f')]
    force: bool,
    /// search for missing dependency commits and output them to stdout
    #[argh(switch, short = 'm')]
    missing: bool,
    /// a Jira ticket to use for commits
    #[argh(option, short = 'j')]
    jira: Option<String>,
    /// the RPC endpoint for inference
    #[argh(option)]
    rpc: Option<String>,
    /// do not submit telemetry data
    #[argh(switch)]
    no_telemetry: bool,
    /// the commit id to apply (cherry-pick)
    #[argh(positional)]
    commit: OsString,
    /// multiple commit ids can be specified
    #[argh(positional)]
    commits: Vec<OsString>,
}


fn main() -> Result<ExitCode, String> {
    let args: Args = argh::from_env();
    let (upstream_repo, downstream_repo) = utils::open_repos(args.git.as_deref())?;
    let app = app::App::new(args.force, args.missing, !args.no_telemetry);
    let workspace = workspace::Workspace::new(
        app.clone(),
        upstream_repo,
        downstream_repo,
        workspace::Overrides::None,
        utils::create_rpc(args.rpc),
        utils::build_commit_headers(args.jira.as_deref())?,
    );
    workspace.push_commit(&args.commit)?;
    for commit in args.commits {
        workspace.push_commit(&commit)?;
    }
    app.run(workspace).map(ExitCode::from)
}
