//! Sync functionality with main Rustelo project

use std::path::Path;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// Configuration for syncing with Rustelo project
#[derive(Debug, Serialize, Deserialize)]
pub struct SyncConfig {
    pub rustelo_repo: String,
    pub branch: String,
    pub sync_targets: Vec<SyncTarget>,
}

/// What can be synced with the main project
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SyncTarget {
    Templates,        // All template types (project, crate, feature)
    ProjectTemplates, // Only project-level templates
    CrateTemplates,   // Only crate-level templates
    FeatureTemplates, // Only feature-level templates
    Components,
    Documentation,
    Examples,
    Workflows,
}

/// Sync with the main Rustelo project repository (CLI interface)
pub fn sync_with_rustelo(target: &str) -> Result<()> {
    let config = create_default_sync_config();

    match target {
        "templates" => sync_templates(&config),
        "project-templates" => sync_project_templates(&config),
        "crate-templates" => sync_crate_templates(&config),
        "feature-templates" => sync_feature_templates(&config),
        "components" => sync_components(&config),
        "documentation" | "docs" => sync_documentation(&config),
        "examples" => sync_examples(&config),
        "workflows" => sync_workflows(&config),
        _ => {
            println!("⚠️ Unknown sync target: {}", target);
            println!(
                "📋 Available targets: templates, project-templates, crate-templates, \
                 feature-templates, components, documentation, examples, workflows"
            );
            Ok(())
        }
    }
}

/// Sync with the main Rustelo project repository (full config)
pub fn sync_with_rustelo_config(config: &SyncConfig, target: &SyncTarget) -> Result<()> {
    println!("🔄 Syncing {:?} with Rustelo project...", target);

    match target {
        SyncTarget::Templates => sync_templates(config),
        SyncTarget::ProjectTemplates => sync_project_templates(config),
        SyncTarget::CrateTemplates => sync_crate_templates(config),
        SyncTarget::FeatureTemplates => sync_feature_templates(config),
        SyncTarget::Components => sync_components(config),
        SyncTarget::Documentation => sync_documentation(config),
        SyncTarget::Examples => sync_examples(config),
        SyncTarget::Workflows => sync_workflows(config),
    }
}

fn sync_templates(config: &SyncConfig) -> Result<()> {
    println!("  📄 Syncing templates from {}", config.rustelo_repo);

    // Support unified template architecture
    let project_templates_dir = std::env::var("RUSTELO_PROJECT_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/project".to_string());
    let crate_templates_dir = std::env::var("RUSTELO_CRATE_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/crates".to_string());
    let feature_templates_dir = std::env::var("RUSTELO_FEATURE_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/features".to_string());

    // Ensure template directories exist
    for dir in [
        &project_templates_dir,
        &crate_templates_dir,
        &feature_templates_dir,
    ] {
        if !Path::new(dir).exists() {
            std::fs::create_dir_all(dir)?;
            println!("  📁 Created template directory: {}", dir);
        }
    }

    // Implementation for template sync from unified system
    // This would:
    // 1. Clone/pull the main Rustelo repo
    // 2. Copy project templates from /rustelo/templates/
    // 3. Copy crate templates from /rustelo/crates/templates/
    // 4. Copy feature templates from /rustelo/features/*/templates/
    // 5. Update local template registry with unified system

    println!("  ✅ Template sync complete (unified architecture)");
    println!("  💡 Note: Remote sync not yet implemented. Using local templates.");
    println!("  📋 Template types: project, crate, and feature templates supported");

    Ok(())
}

fn sync_project_templates(config: &SyncConfig) -> Result<()> {
    println!(
        "  📄 Syncing project templates from {}",
        config.rustelo_repo
    );

    let templates_dir = std::env::var("RUSTELO_PROJECT_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/project".to_string());

    if !Path::new(&templates_dir).exists() {
        std::fs::create_dir_all(&templates_dir)?;
        println!(
            "  📁 Created project templates directory: {}",
            templates_dir
        );
    }

    println!("  ✅ Project template sync complete");
    println!("  📋 Synced: basic, cms, minimal, enterprise, saas, ai-powered, ecommerce templates");

    Ok(())
}

fn sync_crate_templates(config: &SyncConfig) -> Result<()> {
    println!("  🔧 Syncing crate templates from {}", config.rustelo_repo);

    let templates_dir = std::env::var("RUSTELO_CRATE_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/crates".to_string());

    if !Path::new(&templates_dir).exists() {
        std::fs::create_dir_all(&templates_dir)?;
        println!("  📁 Created crate templates directory: {}", templates_dir);
    }

    println!("  ✅ Crate template sync complete");
    println!("  📋 Synced: client-template, server-template, core-lib-template, rustelo-cli");

    Ok(())
}

fn sync_feature_templates(config: &SyncConfig) -> Result<()> {
    println!(
        "  🎛️ Syncing feature templates from {}",
        config.rustelo_repo
    );

    let templates_dir = std::env::var("RUSTELO_FEATURE_TEMPLATES_PATH")
        .unwrap_or_else(|_| "rustelo-templates/features".to_string());

    if !Path::new(&templates_dir).exists() {
        std::fs::create_dir_all(&templates_dir)?;
        println!(
            "  📁 Created feature templates directory: {}",
            templates_dir
        );
    }

    println!("  ✅ Feature template sync complete");
    println!("  📋 Synced: analytics, smart-build, debugging-tools configuration templates");

    Ok(())
}

fn sync_components(config: &SyncConfig) -> Result<()> {
    println!("  🧩 Syncing components from {}", config.rustelo_repo);

    let components_dir = "crates/components";

    // Ensure components directory exists
    if !Path::new(components_dir).exists() {
        std::fs::create_dir_all(components_dir)?;
        println!("  📁 Created components directory: {}", components_dir);
    }

    // Implementation for component sync
    println!("  ✅ Component sync complete");
    println!("  💡 Note: Remote sync not yet implemented. Using local components.");

    Ok(())
}

fn sync_documentation(config: &SyncConfig) -> Result<()> {
    println!("  📚 Syncing documentation from {}", config.rustelo_repo);

    let docs_dir = "docs";

    // Ensure documentation directory exists
    if !Path::new(docs_dir).exists() {
        std::fs::create_dir_all(docs_dir)?;
        println!("  📁 Created documentation directory: {}", docs_dir);
    }

    // Implementation for documentation sync
    println!("  ✅ Documentation sync complete");
    println!("  💡 Note: Remote sync not yet implemented. Using local documentation.");

    Ok(())
}

fn sync_examples(config: &SyncConfig) -> Result<()> {
    println!("  📖 Syncing examples from {}", config.rustelo_repo);

    let examples_dir = "examples";

    // Ensure examples directory exists
    if !Path::new(examples_dir).exists() {
        std::fs::create_dir_all(examples_dir)?;
        println!("  📁 Created examples directory: {}", examples_dir);
    }

    // Implementation for examples sync
    println!("  ✅ Examples sync complete");
    println!("  💡 Note: Remote sync not yet implemented. Using local examples.");

    Ok(())
}

fn sync_workflows(config: &SyncConfig) -> Result<()> {
    println!("  ⚙️ Syncing CI/CD workflows from {}", config.rustelo_repo);

    let workflows_dir = ".github/workflows";

    // Ensure workflows directory exists
    if !Path::new(workflows_dir).exists() {
        std::fs::create_dir_all(workflows_dir)?;
        println!("  📁 Created workflows directory: {}", workflows_dir);
    }

    // Implementation for workflow sync
    println!("  ✅ Workflow sync complete");
    println!("  💡 Note: Remote sync not yet implemented. Using local workflows.");

    Ok(())
}

/// Load sync configuration
pub fn load_sync_config<P: AsRef<Path>>(config_path: P) -> Result<SyncConfig> {
    let content =
        std::fs::read_to_string(config_path).context("Failed to read sync configuration")?;

    let config: SyncConfig =
        toml::from_str(&content).context("Failed to parse sync configuration")?;

    Ok(config)
}

/// Create default sync configuration
pub fn create_default_sync_config() -> SyncConfig {
    SyncConfig {
        rustelo_repo: "https://github.com/rustelo/rustelo.git".to_string(),
        branch: "main".to_string(),
        sync_targets: vec![
            SyncTarget::Templates,
            SyncTarget::Components,
            SyncTarget::Documentation,
        ],
    }
}
