use std::path::PathBuf;

use rngpui_craby_build::platform::{android as android_build, ios as ios_build};
use rngpui_craby_codegen::codegen;
use rngpui_craby_common::{config::load_config, env::is_initialized};
use log::{debug, info};
use owo_colors::OwoColorize;

use crate::{
    commands::build::validate_schema,
    utils::{
        build_targets::{get_build_targets, print_build_targets},
        terminal::with_spinner,
    },
};

pub struct BuildOptions {
    pub project_root: PathBuf,
}

pub fn perform(opts: BuildOptions) -> anyhow::Result<()> {
    let config = load_config(&opts.project_root)?;

    if !is_initialized(&opts.project_root) {
        anyhow::bail!("Craby project is not initialized. Please run `craby init` first.");
    }

    let build_targets = get_build_targets(&config)?;
    if build_targets.is_empty() {
        anyhow::bail!("No build targets found. Please check your `craby.toml` file.");
    }

    debug!(
        "Collecting source files to validate schema(s)... ({})",
        config.source_dir.display()
    );
    let schemas = codegen(rngpui_craby_codegen::CodegenOptions {
        project_root: &opts.project_root,
        source_dir: &config.source_dir,
    })?;
    let total_schemas = schemas.len();
    debug!("{} module schema(s) found", total_schemas);

    validate_schema(&opts.project_root, &schemas)?;

    info!("Starting to build the Cargo project...");
    print_build_targets(&build_targets);
    with_spinner("Building Cargo projects...", |pb| {
        for (i, target) in build_targets.iter().enumerate() {
            pb.set_message(format!(
                "[{}/{}] Building for target: {}",
                i + 1,
                build_targets.len(),
                target.to_str().dimmed()
            ));
            rngpui_craby_build::cargo::build::build_target(&opts.project_root, target)?;
        }
        Ok(())
    })?;
    info!("Cargo project build completed successfully");

    info!("Creating Android artifacts...");
    android_build::crate_libs(&config, &build_targets)?;

    info!("Creating iOS XCFramework...");
    ios_build::crate_libs(&config, &build_targets)?;

    info!("Build completed successfully 🎉");

    Ok(())
}
