use std::path::Path;

use ambient_ci::{
    action::Context,
    plan::RunnablePlan,
    runlog::{RunLog, RunLogSource},
};

const PLAN_FILENAME: &str = "plan.yaml";

fn main() {
    let mut runlog = RunLog::default();
    runlog.stdout();
    let mut context = Context::new(&mut runlog);
    if let Err(err) = fallible_main(&mut context) {
        eprintln!("ERROR: {err}");
        let mut source = err.source();
        while let Some(src) = source {
            eprintln!("caused by: {src}");
            source = src.source();
        }
        context
            .runlog()
            .executor_ends_in_failure(RunLogSource::Plan, 1);
        std::process::exit(1);
    }
}

fn fallible_main(context: &mut Context) -> Result<(), Box<dyn std::error::Error>> {
    let name = "ambient-execute-plan";
    let version = env!("VERSION");

    context.set_env("HOME", "/root");
    context
        .runlog()
        .executor_starts(RunLogSource::Plan, name, version);

    let plan = RunnablePlan::from_file(Path::new(PLAN_FILENAME))?;
    context.runlog().runnable_plan(RunLogSource::Plan, &plan);
    context.set_envs_from_plan(&plan)?;
    plan.execute(RunLogSource::Plan, context)?;

    context
        .runlog()
        .executor_ends_successfully(RunLogSource::Plan);

    Ok(())
}
