//! Project template service for generating project files
//!
//! This service coordinates template generation across specialized modules:
//! - Rust templates (Cargo.toml, main.rs, build.rs)
//! - Infrastructure templates (docker-compose.yml, .env)
//! - Meta templates (README.md, .gitignore, package.json)
//! - Embedded directory structure
//!
//! # Architecture
//!
//! Templates are organized into focused modules under `crate::templates`:
//! - **RustTemplates**: Rust-specific files
//! - **InfraTemplates**: Infrastructure files
//! - **MetaTemplates**: Project metadata files
//! - **EmbeddedTemplates**: Directory structure
//!
//! Template content is stored in external files at `packages/cli/templates/`
//! and embedded at compile time using `include_str!()`.

use crate::templates::{EmbeddedTemplates, InfraTemplates, MetaTemplates, RustTemplates};
use anyhow::{Context, Result};
use std::path::Path;

// Embedded configuration templates
const MECHA10_JSON_TEMPLATE: &str = include_str!("../../templates/config/mecha10.json.template");
const MODEL_JSON_TEMPLATE: &str = include_str!("../../templates/config/model.json.template");
const ENVIRONMENT_JSON_TEMPLATE: &str = include_str!("../../templates/config/environment.json.template");

// Embedded node configuration templates
const BEHAVIOR_EXECUTOR_CONFIG: &str = include_str!("../../templates/config/nodes/behavior-executor/config.json");
const IMAGE_CLASSIFIER_CONFIG: &str = include_str!("../../templates/config/nodes/image-classifier/config.json");
const LLM_COMMAND_CONFIG: &str = include_str!("../../templates/config/nodes/llm-command/config.json");
const OBJECT_DETECTOR_CONFIG: &str = include_str!("../../templates/config/nodes/object-detector/config.json");
const SIMULATION_BRIDGE_CONFIG: &str = include_str!("../../templates/config/nodes/simulation-bridge/config.json");
const WEBSOCKET_BRIDGE_CONFIG: &str = include_str!("../../templates/config/nodes/websocket-bridge/config.json");

// Embedded simulation image assets (for standalone mode)
const AIKO_IMAGE: &[u8] = include_bytes!("../../templates/assets/images/aiko.jpg");
const PHOEBE_IMAGE: &[u8] = include_bytes!("../../templates/assets/images/phoebe.jpg");
const CAT_TOWER_IMAGE: &[u8] = include_bytes!("../../templates/assets/cat_tower.jpg");

// Embedded behavior tree templates (for standalone mode)
const BEHAVIOR_BASIC_NAVIGATION: &str = include_str!("../../templates/behaviors/basic_navigation.json");
const BEHAVIOR_IDLE_WANDER: &str = include_str!("../../templates/behaviors/idle_wander.json");
const BEHAVIOR_OBSTACLE_AVOIDANCE: &str = include_str!("../../templates/behaviors/obstacle_avoidance.json");
const BEHAVIOR_PATROL_SIMPLE: &str = include_str!("../../templates/behaviors/patrol_simple.json");

// Embedded simulation configs (for standalone mode)
const SIMULATION_CONFIG_DEV: &str = include_str!("../../templates/config/simulation/dev/config.json");
const SIMULATION_CONFIG_PRODUCTION: &str = include_str!("../../templates/config/simulation/production/config.json");

// Embedded simulation docker files (for standalone mode)
const SIMULATION_DOCKERFILE: &str = include_str!("../../templates/docker/simulation/Dockerfile");
const SIMULATION_ENTRYPOINT: &str = include_str!("../../templates/docker/simulation/entrypoint.sh");
const SIMULATION_DOCKERIGNORE: &str = include_str!("../../templates/docker/simulation/.dockerignore");

/// Service for generating project template files
///
/// # Examples
///
/// ```rust,ignore
/// use mecha10_cli::services::ProjectTemplateService;
///
/// let service = ProjectTemplateService::new();
///
/// // Generate all project files
/// service.create_readme(&project_path, "my-robot").await?;
/// service.create_cargo_toml(&project_path, "my-robot", false).await?;
/// ```
pub struct ProjectTemplateService {
    rust: RustTemplates,
    infra: InfraTemplates,
    meta: MetaTemplates,
    embedded: EmbeddedTemplates,
}

impl ProjectTemplateService {
    /// Create a new ProjectTemplateService
    pub fn new() -> Self {
        Self {
            rust: RustTemplates::new(),
            infra: InfraTemplates::new(),
            meta: MetaTemplates::new(),
            embedded: EmbeddedTemplates::new(),
        }
    }

    /// Create README.md for the project
    pub async fn create_readme(&self, path: &Path, project_name: &str) -> Result<()> {
        self.meta.create_readme(path, project_name).await
    }

    /// Create .gitignore for the project
    pub async fn create_gitignore(&self, path: &Path) -> Result<()> {
        self.meta.create_gitignore(path).await
    }

    /// Create .cargo/config.toml for framework development
    ///
    /// This patches all mecha10-* dependencies to use local paths instead of crates.io.
    /// Requires a framework_path pointing to the mecha10-monorepo root.
    pub async fn create_cargo_config(&self, path: &Path, framework_path: &str) -> Result<()> {
        self.rust.create_cargo_config(path, framework_path).await
    }

    /// Create Cargo.toml for the project
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project
    /// * `dev` - Whether this is for framework development (affects dependency resolution)
    pub async fn create_cargo_toml(&self, path: &Path, project_name: &str, dev: bool) -> Result<()> {
        self.rust.create_cargo_toml(path, project_name, dev).await
    }

    /// Create src/main.rs for the project
    pub async fn create_main_rs(&self, path: &Path, project_name: &str) -> Result<()> {
        self.rust.create_main_rs(path, project_name).await
    }

    /// Create build.rs for the project
    ///
    /// This build script generates:
    /// 1. node_registry.rs - Node dispatcher based on mecha10.json
    /// 2. embedded.rs - Embedded asset accessors
    pub async fn create_build_rs(&self, path: &Path) -> Result<()> {
        self.rust.create_build_rs(path).await
    }

    /// Create embedded directory structure
    pub async fn create_embedded_structure(&self, path: &Path) -> Result<()> {
        self.embedded.create_structure(path).await
    }

    /// Create .env.example for the project
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project
    /// * `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<()> {
        self.infra.create_env_example(path, project_name, framework_path).await
    }

    /// Create rustfmt.toml for the project
    pub async fn create_rustfmt_toml(&self, path: &Path) -> Result<()> {
        self.rust.create_rustfmt_toml(path).await
    }

    /// Create docker-compose.yml for the project
    ///
    /// Generates a Docker Compose file with Redis and optional PostgreSQL services
    /// for local development and deployment.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project (used for container naming)
    pub async fn create_docker_compose(&self, path: &Path, project_name: &str) -> Result<()> {
        self.infra.create_docker_compose(path, project_name).await
    }

    /// Create package.json for npm dependencies
    ///
    /// Includes @mecha10/simulation-models and @mecha10/simulation-environments dependencies.
    /// Resolution happens at runtime via MECHA10_FRAMEWORK_PATH env var:
    /// - If set: Uses local monorepo packages
    /// - If not set: Uses node_modules/@mecha10/* (requires npm install)
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    /// * `project_name` - Name of the project
    pub async fn create_package_json(&self, path: &Path, project_name: &str) -> Result<()> {
        self.meta.create_package_json(path, project_name).await
    }

    /// Create requirements.txt for Python dependencies
    ///
    /// Includes Python packages needed for AI nodes (onnx, onnxruntime).
    /// Install with: `mecha10 setup` or `pip install -r requirements.txt`
    ///
    /// # Arguments
    ///
    /// * `path` - Project root path
    pub async fn create_requirements_txt(&self, path: &Path) -> Result<()> {
        self.meta.create_requirements_txt(path).await
    }

    /// Create mecha10.json configuration file
    ///
    /// Generates the main project configuration file with robot identity,
    /// simulation settings, nodes, services, and Docker configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    /// * `project_name` - Name of the project
    /// * `template` - Robot template (rover, humanoid, etc.)
    pub async fn create_mecha10_json(&self, path: &Path, project_name: &str, template: &Option<String>) -> Result<()> {
        let platform = template.as_deref().unwrap_or("basic");
        let project_id = project_name.replace('-', "_");

        // Render template with handlebars
        let config_content = MECHA10_JSON_TEMPLATE
            .replace("{{project_name}}", project_name)
            .replace("{{project_id}}", &project_id)
            .replace("{{platform}}", platform);

        tokio::fs::write(path.join("mecha10.json"), config_content).await?;
        Ok(())
    }

    /// Create simulation/models/model.json
    ///
    /// Generates the rover robot physical model configuration for Godot simulation
    /// from embedded template.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_simulation_model_json(&self, path: &Path) -> Result<()> {
        let model_dest = path.join("simulation/models/rover/model.json");

        // Ensure destination directory exists
        if let Some(parent) = model_dest.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }

        // Write embedded model.json template
        tokio::fs::write(&model_dest, MODEL_JSON_TEMPLATE)
            .await
            .context("Failed to write model.json")?;

        Ok(())
    }

    /// Create simulation/environments/basic_arena/environment.json
    ///
    /// Generates the basic arena environment configuration for Godot simulation
    /// from embedded template.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_simulation_environment_json(&self, path: &Path) -> Result<()> {
        let env_dest = path.join("simulation/environments/basic_arena/environment.json");

        // Ensure destination directory exists
        if let Some(parent) = env_dest.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }

        // Write embedded environment.json template
        tokio::fs::write(&env_dest, ENVIRONMENT_JSON_TEMPLATE)
            .await
            .context("Failed to write environment.json")?;

        Ok(())
    }

    /// Create node configuration files from embedded templates
    ///
    /// Writes node configs to configs/dev/nodes/{node}/config.json
    /// This is used in standalone mode when framework path is not available.
    ///
    /// Node configs use environment variable placeholders (${CONTROL_PLANE_URL}, ${ROBOT_ID}, etc.)
    /// that are resolved at runtime based on the mecha10.json environments configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_node_configs(&self, path: &Path) -> Result<()> {
        // List of nodes with embedded configs
        // Templates use ${CONTROL_PLANE_URL} which is resolved at runtime from mecha10.json
        let node_configs: &[(&str, &str)] = &[
            ("behavior-executor", BEHAVIOR_EXECUTOR_CONFIG),
            ("image-classifier", IMAGE_CLASSIFIER_CONFIG),
            ("llm-command", LLM_COMMAND_CONFIG),
            ("object-detector", OBJECT_DETECTOR_CONFIG),
            ("simulation-bridge", SIMULATION_BRIDGE_CONFIG),
            ("websocket-bridge", WEBSOCKET_BRIDGE_CONFIG),
        ];

        for (node_name, config_content) in node_configs {
            // Write to dev environment
            let dev_dest = path.join("configs/dev/nodes").join(node_name).join("config.json");

            if let Some(parent) = dev_dest.parent() {
                tokio::fs::create_dir_all(parent).await?;
            }

            tokio::fs::write(&dev_dest, *config_content)
                .await
                .with_context(|| format!("Failed to write {}/config.json", node_name))?;

            // Also write to common (shared across environments)
            let common_dest = path.join("configs/common/nodes").join(node_name).join("config.json");

            if let Some(parent) = common_dest.parent() {
                tokio::fs::create_dir_all(parent).await?;
            }

            tokio::fs::write(&common_dest, *config_content)
                .await
                .with_context(|| format!("Failed to write common/{}/config.json", node_name))?;
        }

        Ok(())
    }

    /// Create simulation image assets from embedded templates
    ///
    /// Writes image assets to assets/images/ directory.
    /// This is used in standalone mode when framework path is not available.
    /// In framework dev mode, these are copied from the simulation package instead.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_simulation_assets(&self, path: &Path) -> Result<()> {
        // Create assets/images directory
        let images_dest = path.join("assets/images");
        tokio::fs::create_dir_all(&images_dest).await?;

        // Write image files
        let image_assets: &[(&str, &[u8])] = &[("aiko.jpg", AIKO_IMAGE), ("phoebe.jpg", PHOEBE_IMAGE)];

        for (filename, content) in image_assets {
            let dest_file = images_dest.join(filename);
            tokio::fs::write(&dest_file, content)
                .await
                .with_context(|| format!("Failed to write assets/images/{}", filename))?;
        }

        // Write cat_tower.jpg to assets/ directory (not images subdirectory)
        let assets_dest = path.join("assets");
        tokio::fs::write(assets_dest.join("cat_tower.jpg"), CAT_TOWER_IMAGE)
            .await
            .context("Failed to write assets/cat_tower.jpg")?;

        Ok(())
    }

    /// Create behavior tree templates from embedded files
    ///
    /// Writes behavior tree JSON files to behaviors/ directory.
    /// This is used in standalone mode when framework path is not available.
    /// In framework dev mode, these are copied from behavior-runtime/seeds/ instead.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_behavior_templates(&self, path: &Path) -> Result<()> {
        let behaviors_dest = path.join("behaviors");
        tokio::fs::create_dir_all(&behaviors_dest).await?;

        let behavior_templates: &[(&str, &str)] = &[
            ("basic_navigation.json", BEHAVIOR_BASIC_NAVIGATION),
            ("idle_wander.json", BEHAVIOR_IDLE_WANDER),
            ("obstacle_avoidance.json", BEHAVIOR_OBSTACLE_AVOIDANCE),
            ("patrol_simple.json", BEHAVIOR_PATROL_SIMPLE),
        ];

        for (filename, content) in behavior_templates {
            let dest_file = behaviors_dest.join(filename);
            tokio::fs::write(&dest_file, *content)
                .await
                .with_context(|| format!("Failed to write behaviors/{}", filename))?;
        }

        Ok(())
    }

    /// Create simulation config files from embedded templates
    ///
    /// Writes simulation configs to configs/{env}/simulation/config.json.
    /// This is used in standalone mode when framework path is not available.
    /// In framework dev mode, these are copied from packages/simulation/configs/ instead.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_simulation_configs(&self, path: &Path) -> Result<()> {
        // Write dev config
        let dev_dest = path.join("configs/dev/simulation/config.json");
        if let Some(parent) = dev_dest.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&dev_dest, SIMULATION_CONFIG_DEV)
            .await
            .context("Failed to write configs/dev/simulation/config.json")?;

        // Write production config
        let prod_dest = path.join("configs/production/simulation/config.json");
        if let Some(parent) = prod_dest.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&prod_dest, SIMULATION_CONFIG_PRODUCTION)
            .await
            .context("Failed to write configs/production/simulation/config.json")?;

        Ok(())
    }

    /// Create simulation Docker files from embedded templates
    ///
    /// Writes Dockerfile, entrypoint.sh, and .dockerignore to simulation/ directory.
    /// This is used in standalone mode when framework path is not available.
    /// In framework dev mode, these are copied from packages/simulation/docker/ instead.
    ///
    /// # Arguments
    ///
    /// * `path` - Project root directory
    pub async fn create_simulation_docker_files(&self, path: &Path) -> Result<()> {
        let simulation_dest = path.join("simulation");
        tokio::fs::create_dir_all(&simulation_dest).await?;

        // Write Dockerfile
        tokio::fs::write(simulation_dest.join("Dockerfile"), SIMULATION_DOCKERFILE)
            .await
            .context("Failed to write simulation/Dockerfile")?;

        // Write entrypoint.sh and make it executable
        let entrypoint_path = simulation_dest.join("entrypoint.sh");
        tokio::fs::write(&entrypoint_path, SIMULATION_ENTRYPOINT)
            .await
            .context("Failed to write simulation/entrypoint.sh")?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = tokio::fs::metadata(&entrypoint_path).await?.permissions();
            perms.set_mode(0o755);
            tokio::fs::set_permissions(&entrypoint_path, perms).await?;
        }

        // Write .dockerignore
        tokio::fs::write(simulation_dest.join(".dockerignore"), SIMULATION_DOCKERIGNORE)
            .await
            .context("Failed to write simulation/.dockerignore")?;

        Ok(())
    }
}

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