use lmrc_config_validator::LmrcConfig;
use lmrc_toml_writer::WorkspaceToml;
use std::fs;
use std::path::Path;

use crate::error::Result;

pub fn generate_workspace_toml(project_path: &Path, config: &LmrcConfig) -> Result<()> {
    let mut builder = WorkspaceToml::new().resolver("2").member("infra/pipeline");

    // Add all applications as members
    for app in &config.apps.applications {
        builder = builder.member(format!("apps/{}", app.name));
    }

    // Set workspace package metadata
    let authors = config
        .infrastructure
        .gitlab
        .as_ref()
        .map(|g| format!("{} Team", g.namespace))
        .unwrap_or_else(|| "LMRC Team".to_string());

    builder = builder
        .workspace_version("0.1.0")
        .workspace_edition("2021")
        .workspace_author(authors);

    // Add infrastructure library dependencies
    builder = builder
        .dependency("lmrc-gitlab", "0.1")
        .dependency("lmrc-hetzner", "0.1")
        .dependency("lmrc-k3s", "0.1")
        .dependency("lmrc-cloudflare", "0.2")
        .dependency("lmrc-postgres", "0.1")
        .dependency("lmrc-ssh", "0.1")
        .dependency("lmrc-docker", "0.1")
        .dependency("lmrc-kubernetes", "0.1");

    // Add common dependencies
    builder = builder
        .dependency("tokio", r#"{ version = "1.0", features = ["full"] }"#)
        .dependency("serde", r#"{ version = "1.0", features = ["derive"] }"#)
        .dependency("serde_json", "1.0")
        .dependency("thiserror", "2.0")
        .dependency("tracing", "0.1")
        .dependency("tracing-subscriber", "0.3")
        .dependency("clap", r#"{ version = "4.5", features = ["derive"] }"#)
        .dependency("toml", "0.8");

    let workspace_toml = builder.build();

    let cargo_path = project_path.join("Cargo.toml");
    fs::write(&cargo_path, workspace_toml)?;

    Ok(())
}
