//! Styling integration for UnoCSS and CSS frameworks

use std::fs;
use std::path::Path;

use anyhow::Result;

use crate::commands::feature::FeatureManifest;

pub struct StylingIntegrator<'a> {
    project_root: &'a Path,
}

impl<'a> StylingIntegrator<'a> {
    pub fn new(project_root: &'a Path) -> Self {
        Self { project_root }
    }

    pub fn integrate(&self, manifest: &FeatureManifest) -> Result<()> {
        println!("  🎨 Integrating styling configuration...");

        // Integrate UnoCSS configuration
        self.integrate_uno_config(manifest)?;

        // Integrate custom CSS
        self.integrate_custom_css(manifest)?;

        println!("    ✅ Styling integrated successfully");
        Ok(())
    }

    fn integrate_uno_config(&self, manifest: &FeatureManifest) -> Result<()> {
        let uno_config = self.project_root.join("uno.config.ts");

        if uno_config.exists() {
            // Read existing config
            let content = fs::read_to_string(&uno_config)?;

            // Check if feature already integrated
            let feature_comment = format!("// {} feature integration", manifest.feature.name);

            if !content.contains(&feature_comment) {
                // Add feature-specific configuration
                let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();

                // Find presets array and add feature presets
                if let Some(presets_line) = lines
                    .iter()
                    .position(|line| line.trim().starts_with("presets:"))
                {
                    // Insert feature presets
                    let comment_line = format!("    {}", feature_comment);
                    lines.insert(presets_line + 1, comment_line);

                    // Add actual preset imports here based on manifest
                    // This would be implemented based on
                    // manifest.styles.uno.presets
                }

                let updated_content = lines.join("\n");
                fs::write(&uno_config, updated_content)?;

                println!("    ✓ Updated UnoCSS configuration");
            } else {
                println!("    ↪ UnoCSS configuration already includes this feature");
            }
        } else {
            println!("    ↪ No uno.config.ts found, skipping UnoCSS integration");
        }

        Ok(())
    }

    fn integrate_custom_css(&self, _manifest: &FeatureManifest) -> Result<()> {
        // Integrate custom CSS files if specified in manifest
        // This would copy CSS files from the feature to the project
        Ok(())
    }
}
