//! Infrastructure template generation
//!
//! Handles generation of infrastructure files:
//! - docker-compose.yml
//! - .env.example

use anyhow::Result;
use std::path::Path;

/// Template files embedded at compile time
const DOCKER_COMPOSE: &str = include_str!("../../templates/docker-compose.yml.template");
const ENV_EXAMPLE: &str = include_str!("../../templates/.env.example.template");

/// Infrastructure template generator
pub struct InfraTemplates;

impl InfraTemplates {
    /// Create a new InfraTemplates instance
    pub fn new() -> Self {
        Self
    }

    /// Create docker-compose.yml for the project
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project
    pub async fn create_docker_compose(&self, path: &Path, project_name: &str) -> Result<()> {
        let content = DOCKER_COMPOSE.replace("{{project_name}}", project_name);
        tokio::fs::write(path.join("docker-compose.yml"), content).await?;
        Ok(())
    }

    /// Create .env.example for the project
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project (used for ROBOT_ID)
    /// * `framework_path` - Optional framework path for development mode
    pub async fn create_env_example(
        &self,
        path: &Path,
        project_name: &str,
        framework_path: Option<String>,
    ) -> Result<()> {
        let robot_id = project_name.replace('-', "_");

        // If framework path is provided, uncomment and set it
        let framework_line = if let Some(fw_path) = framework_path {
            format!("MECHA10_FRAMEWORK_PATH={}", fw_path)
        } else {
            "# MECHA10_FRAMEWORK_PATH=/path/to/mecha10-monorepo".to_string()
        };

        let content = ENV_EXAMPLE
            .replace("{{robot_id}}", &robot_id)
            .replace("# MECHA10_FRAMEWORK_PATH=/path/to/mecha10-monorepo", &framework_line);

        // Write .env.example
        tokio::fs::write(path.join(".env.example"), &content).await?;

        // Also create .env from .env.example (users need this for the CLI to load variables)
        tokio::fs::write(path.join(".env"), &content).await?;

        Ok(())
    }
}

impl Default for InfraTemplates {
    fn default() -> Self {
        Self::new()
    }
}
