//! Migration handler for bootstrapping existing projects into lifecycle management.

use crate::ui_config;
use anyhow::Result;
use std::path::{Path, PathBuf};
use syntaxis_core::migration::ProjectMigrator;

/// Handler for project migration operations
#[derive(Debug)]
pub struct MigrationHandler;

impl MigrationHandler {
    /// Migrate an existing project to lifecycle management
    pub async fn migrate(project_path: &str, create_backup: bool) -> Result<()> {
        println!("🔄 Migrating project from: {}", project_path);

        // Create backup if requested
        if create_backup {
            println!("  📦 Creating backup before migration...");
            // Backup logic would go here
        }

        // Detect project type
        println!("  🔍 Detecting project type...");
        let migrator = ProjectMigrator::new(PathBuf::from(project_path));
        let detected = migrator
            .detect_project()
            .map_err(|e| anyhow::anyhow!("Failed to detect project: {}", e))?;

        println!("  ✓ Detected: {:?}", detected.project_type);
        println!("  ✓ Name: {}", detected.name);
        if let Some(desc) = &detected.description {
            println!("  ✓ Description: {}", desc);
        }

        // Migrate to config
        println!("  📝 Converting to lifecycle config...");
        let config = migrator
            .migrate_to_config(&detected)
            .map_err(|e| anyhow::anyhow!("Failed to migrate config: {}", e))?;

        // Initialize workspace
        println!("  📁 Initializing workspace structure...");
        migrator
            .initialize_workspace(&config)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to initialize workspace: {}", e))?;

        println!("\n✅ Project successfully migrated!");
        println!("  Config: .project/lifecycle.toml");
        println!("  Metadata: .project/tracking/");
        println!("  Security: .project/sbom/");
        println!("  Backups: .project/backups/");

        Ok(())
    }

    /// Show migration status for a project
    #[allow(dead_code)]
    pub fn show_migration_status(project_path: &str) -> Result<()> {
        println!("📊 Migration status for: {}", project_path);

        let path = Path::new(project_path);
        if path.join(".project").exists() {
            println!("  ✓ Already migrated to lifecycle management");
            if path.join(".project/lifecycle.toml").exists() {
                println!("  ✓ Configuration file: .project/lifecycle.toml");
            }
            if path.join(".project/tracking").exists() {
                println!("  ✓ Tracking directory: .project/tracking/");
            }
        } else {
            println!("  ✗ Not yet migrated to lifecycle management");
            let app_name = ui_config::get_app_name();
            println!("  Run '{} migrate {}' to proceed", app_name, project_path);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_migration_handler_creation() {
        let handler = MigrationHandler;
        assert_eq!(format!("{:?}", handler), "MigrationHandler");
    }

    #[tokio::test]
    async fn test_migrate_invalid_path() {
        let result = MigrationHandler::migrate("/nonexistent/path", false).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_migration_status_nonexistent() {
        let result = MigrationHandler::show_migration_status("/tmp/nonexistent-project");
        assert!(result.is_ok());
    }
}
