use semver::{Version, VersionReq};
use regex::Regex;

/// Normalize a version string to be semver compatible
pub fn normalize_version(version_str: &str) -> String {
    // If already starts with a digit, assume semantic version format
    if version_str.chars().next().map_or(false, |c| c.is_ascii_digit()) {
        // Clean up any common prefixes like 'v'
        let cleaned = version_str.trim_start_matches(|c| c == 'v' || c == 'V');
        return cleaned.to_string();
    }

    // Return as-is for now
    version_str.to_string()
}

/// Compare two plugin versions to determine if an update is available
pub fn compare_plugin_versions(installed_str: &str, repo_str: &str) -> bool {
    // Normalize version strings
    let installed_version = normalize_version(installed_str);
    let repo_version = normalize_version(repo_str);

    // Try to parse as semver
    match (Version::parse(&installed_version), Version::parse(&repo_version)) {
        (Ok(installed), Ok(repo)) => {
            // Simple semver comparison
            repo > installed
        },
        _ => {
            // Fallback to simple string comparison for non-semver versions
            repo_version != installed_version
        }
    }
}

/// Extract version pattern from a string
pub fn extract_version_pattern(input: &str) -> Option<String> {
    // Look for version pattern like 1.19.2 in string
    let version_pattern = Regex::new(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)").unwrap();
    if let Some(captures) = version_pattern.captures(input) {
        if let Some(version_match) = captures.get(0) {
            return Some(version_match.as_str().to_string());
        }
    }
    None
}

/// Check if a plugin version is compatible with a specific Minecraft version
pub fn is_version_compatible(plugin_version: &str, minecraft_version: &str) -> bool {
    // Try to parse the Minecraft version
    if let Ok(mc_version) = Version::parse(minecraft_version) {
        // Try to parse as a version requirement
        if let Ok(req) = VersionReq::parse(plugin_version) {
            return req.matches(&mc_version);
        }
    }

    // If version formats are incompatible, make best guess
    plugin_version.contains(minecraft_version)
}