use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Deserialize, Serialize, Debug)]
pub struct PackageJson {
    pub dependencies: Option<HashMap<String, String>>,
    #[serde(rename = "devDependencies")]
    pub dev_dependencies: Option<HashMap<String, String>>,
    #[serde(rename = "packageManager")]
    pub package_manager: Option<String>,
}

#[derive(Debug, Clone)]
pub enum PackageManager {
    Npm,
    Yarn,
    Pnpm,
    Rush,
}

impl PackageManager {
    pub fn install_command(&self) -> &str {
        match self {
            PackageManager::Npm => "npm",
            PackageManager::Yarn => "yarn",
            PackageManager::Pnpm => "pnpm",
            PackageManager::Rush => "rush",
        }
    }

    /// 从 packageManager 字段解析包管理器
    pub fn from_package_manager_field(package_manager: &str) -> Option<Self> {
        // packageManager 字段格式通常是 "pnpm@8.6.0" 或 "yarn@1.22.19" 等
        let manager_name = package_manager.split('@').next()?;
        match manager_name {
            "npm" => Some(PackageManager::Npm),
            "yarn" => Some(PackageManager::Yarn),
            "pnpm" => Some(PackageManager::Pnpm),
            "rush" => Some(PackageManager::Rush),
            _ => None,
        }
    }

    pub fn install_args(&self, dev: bool) -> Vec<&str> {
        match self {
            PackageManager::Npm => {
                if dev {
                    vec!["install", "--save-dev"]
                } else {
                    vec!["install", "--save"]
                }
            }
            PackageManager::Yarn => {
                if dev {
                    vec!["add", "--dev"]
                } else {
                    vec!["add"]
                }
            }
            PackageManager::Pnpm => {
                if dev {
                    vec!["add", "-D"]
                } else {
                    vec!["add"]
                }
            }
            PackageManager::Rush => {
                if dev {
                    vec!["add", "--dev"]
                } else {
                    vec!["add"]
                }
            }
        }
    }
}