//! Environment variable integration

use std::fs;
use std::path::Path;

use anyhow::Result;

use crate::commands::feature::FeatureManifest;

pub struct EnvironmentIntegrator<'a> {
    project_root: &'a Path,
}

impl<'a> EnvironmentIntegrator<'a> {
    pub fn new(project_root: &'a Path) -> Self {
        Self { project_root }
    }

    pub fn integrate(&self, manifest: &FeatureManifest) -> Result<()> {
        println!("  🔧 Integrating environment variables...");

        if let Some(env_config) = &manifest.environment {
            let env_file = self.project_root.join(".env");

            // Load existing .env or create header
            let mut env_content = if env_file.exists() {
                fs::read_to_string(&env_file)?
            } else {
                String::from("# Rustelo Feature Environment Configuration\n")
            };

            // Add feature section header
            let section_header = format!(
                "\n# {} Feature Configuration\n",
                manifest.feature.name.to_uppercase()
            );
            if !env_content.contains(section_header.trim()) {
                env_content.push_str(&section_header);

                // Add each environment variable
                for var in &env_config.variables {
                    let var_line = if var.secret.unwrap_or(false) {
                        format!(
                            "# {}: REQUIRED SECRET - Keep secure!\n{}=\n",
                            var.name, var.name
                        )
                    } else if var.required {
                        format!("# {}: REQUIRED\n{}={}\n", var.name, var.name, var.default)
                    } else {
                        format!(
                            "# {}: Optional (default: {})\n{}={}\n",
                            var.name, var.default, var.name, var.default
                        )
                    };

                    env_content.push_str(&var_line);
                    println!("    ✓ Added environment variable: {}", var.name);
                }

                // Write updated .env file
                fs::write(&env_file, env_content)?;
                println!("    ✅ Environment variables integrated successfully");
            } else {
                println!("    ↪ Feature environment already configured");
            }
        } else {
            println!("    ↪ No environment configuration in feature manifest");
        }

        Ok(())
    }
}
