//! Infrastructure integration for Docker, deployment configs

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

use anyhow::Result;

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

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

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

    pub fn integrate(&self, manifest: &FeatureManifest) -> Result<()> {
        println!("  🐳 Integrating infrastructure configuration...");

        // Integrate Docker configuration
        self.integrate_docker_config(manifest)?;

        // Integrate deployment scripts
        self.integrate_deployment_config(manifest)?;

        println!("    ✅ Infrastructure integrated successfully");
        Ok(())
    }

    fn integrate_docker_config(&self, manifest: &FeatureManifest) -> Result<()> {
        let docker_compose = self.project_root.join("docker-compose.yml");

        if docker_compose.exists() {
            // Read existing docker-compose.yml
            let content = fs::read_to_string(&docker_compose)?;

            // Check if feature services already added
            let feature_comment = format!("# {} feature services", manifest.feature.name);

            if !content.contains(&feature_comment) {
                // Add feature services to docker-compose
                let updated_content = format!(
                    "{}

{}
# Add {} services here",
                    content, feature_comment, manifest.feature.name
                );
                fs::write(&docker_compose, updated_content)?;

                println!("    ✓ Updated docker-compose.yml");
            } else {
                println!("    ↪ Docker compose already includes this feature");
            }
        } else {
            println!("    ↪ No docker-compose.yml found, skipping Docker integration");
        }

        Ok(())
    }

    fn integrate_deployment_config(&self, _manifest: &FeatureManifest) -> Result<()> {
        // Integrate deployment configuration
        // This would handle deployment scripts, CI/CD configs, etc.
        Ok(())
    }
}
