use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
use sha2::{Sha256, Digest};

/// Calculate SHA-256 hash of a file for identification and verification
pub fn calculate_file_hash(file_path: &str) -> Result<String, String> {
    // Open the file
    let mut file = match File::open(file_path) {
        Ok(file) => file,
        Err(e) => return Err(format!("Failed to open file for hashing: {}", e)),
    };

    // Read the file content
    let mut buffer = Vec::new();
    if let Err(e) = file.read_to_end(&mut buffer) {
        return Err(format!("Failed to read file for hashing: {}", e));
    }

    // Calculate the SHA-256 hash
    let mut hasher = Sha256::new();
    hasher.update(&buffer);
    let result = hasher.finalize();

    // Convert the hash to a hex string
    let hash_string = format!("{:x}", result);
    Ok(hash_string)
}

/// Check if a file is currently locked by another process
pub fn is_file_locked(file_path: &str) -> bool {
    // Try to open the file with write permissions to check if locked
    match fs::OpenOptions::new()
        .write(true)
        .open(file_path)
    {
        Ok(_) => false, // File can be opened for writing, so it's not locked
        Err(_) => {
            // If we can't open for writing, try to check if it exists
            // This helps determine if the error is due to file being locked
            // or just not existing
            Path::new(file_path).exists()
        }
    }
}

/// Read YAML content from a ZIP archive
pub fn read_yaml_from_archive(archive: &mut zip::ZipArchive<fs::File>, file_name: &str) -> Result<String, String> {
    match archive.by_name(file_name) {
        Ok(mut file) => {
            let mut contents = String::new();
            file.read_to_string(&mut contents)
                .map_err(|e| format!("Failed to read {}: {}", file_name, e))?;
            Ok(contents)
        },
        Err(e) => Err(format!("Failed to find {}: {}", file_name, e))
    }
}