//! Recent projects management
//!
//! Stores and retrieves recently opened projects for quick access.

use std::path::PathBuf;

use serde::{
    Deserialize,
    Serialize,
};

const MAX_RECENT_PROJECTS: usize = 10;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecentProject {
    pub path: PathBuf,
    pub name: String,
    pub last_opened: String, // ISO 8601 timestamp
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RecentProjects {
    pub projects: Vec<RecentProject>,
}

impl RecentProjects {
    /// Load recent projects from disk
    pub fn load() -> Self {
        let config_path = Self::config_path();

        if let Ok(contents) = std::fs::read_to_string(&config_path) {
            if let Ok(recent) = serde_json::from_str(&contents) {
                return recent;
            }
        }

        Self::default()
    }

    /// Save recent projects to disk
    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
        let config_path = Self::config_path();

        // Ensure parent directory exists
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let json = serde_json::to_string_pretty(self)?;
        std::fs::write(&config_path, json)?;

        Ok(())
    }

    /// Add a project to the recent list
    pub fn add(&mut self, path: PathBuf) {
        let name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        let now = chrono::Utc::now().to_rfc3339();

        // Remove if already exists
        self.projects.retain(|p| p.path != path);

        // Add to front
        self.projects.insert(
            0,
            RecentProject {
                path,
                name,
                last_opened: now,
            },
        );

        // Limit to MAX_RECENT_PROJECTS
        self.projects.truncate(MAX_RECENT_PROJECTS);

        // Save to disk
        let _ = self.save();
    }

    /// Get the config file path
    fn config_path() -> PathBuf {
        if let Some(home) = dirs::home_dir() {
            home.join(".config")
                .join("storybook-editor")
                .join("recent_projects.json")
        } else {
            PathBuf::from("recent_projects.json")
        }
    }
}
