//! `keg docker` command — Generate Dockerfile and docker-compose.yml

use anyhow::{Context, Result};
use console::{style, Emoji};
use std::fs;
use std::path::Path;

/// Generate Dockerfile and docker-compose.yml
pub fn docker() -> Result<()> {
    println!();
    println!("{} {}", Emoji("🐳", ""), style("Generating Docker files").bold());
    println!();

    let project_name = std::env::current_dir()
        .ok()
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
        .unwrap_or_else(|| "app".to_string());

    let replacements: &[(&str, &str)] = &[("{{PROJECT_NAME}}", project_name.as_str())];

    // Dockerfile
    let df_path = Path::new("Dockerfile");
    if df_path.exists() {
        println!("  {} {} already exists, skipping", style("⚠").yellow(), style("Dockerfile").dim());
    } else {
        fs::write(df_path, render_template(include_str!("../templates/dockerfile_txt.txt"), replacements))
            .context("Failed to write Dockerfile")?;
        println!("  {} {}", style("✓").green(), style("Dockerfile").dim());
    }

    // docker-compose.yml
    let dc_path = Path::new("docker-compose.yml");
    if dc_path.exists() {
        println!("  {} {} already exists, skipping", style("⚠").yellow(), style("docker-compose.yml").dim());
    } else {
        fs::write(dc_path, render_template(include_str!("../templates/docker_compose_yml.txt"), replacements))
            .context("Failed to write docker-compose.yml")?;
        println!("  {} {}", style("✓").green(), style("docker-compose.yml").dim());
    }

    println!();
    println!("{} {}", Emoji("✨", ""), style("Docker files generated!").green());
    println!();
    println!("  {} {} docker-compose up -d", style("→").cyan(), style("Start services").dim());
    println!();

    Ok(())
}

fn render_template(content: &str, replacements: &[(&str, &str)]) -> String {
    let mut result = content.to_string();
    for (placeholder, value) in replacements {
        result = result.replace(placeholder, value);
    }
    result
}