use std::fs;
use std::path::Path;
use base64::{Engine as _, engine::general_purpose};
use tauri::command;

/// 读取图片文件并返回base64编码的数据URL
#[command]
pub async fn read_image_as_data_url(file_path: String) -> Result<String, String> {
    let path = Path::new(&file_path);
    
    // 检查文件是否存在
    if !path.exists() {
        return Err("File does not exist".to_string());
    }
    
    // 检查是否是图片文件
    let extension = path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_lowercase())
        .unwrap_or_default();
    
    let mime_type = match extension.as_str() {
        "jpg" | "jpeg" => "image/jpeg",
        "png" => "image/png",
        "gif" => "image/gif",
        "bmp" => "image/bmp",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        _ => return Err("Unsupported image format".to_string()),
    };
    
    // 读取文件内容
    match fs::read(&file_path) {
        Ok(file_data) => {
            // 编码为base64
            let base64_data = general_purpose::STANDARD.encode(&file_data);
            // 返回data URL格式
            Ok(format!("data:{};base64,{}", mime_type, base64_data))
        }
        Err(e) => Err(format!("Failed to read file: {}", e)),
    }
}

/// 读取视频文件并返回base64编码的数据URL
#[command]
pub async fn read_video_as_data_url(file_path: String) -> Result<String, String> {
    let path = Path::new(&file_path);

    // 检查文件是否存在
    if !path.exists() {
        return Err("File does not exist".to_string());
    }

    // 检查是否是视频文件
    let extension = path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_lowercase())
        .unwrap_or_default();

    let mime_type = match extension.as_str() {
        "mp4" => "video/mp4",
        "avi" => "video/x-msvideo",
        "mov" => "video/quicktime",
        "mkv" => "video/x-matroska",
        "wmv" => "video/x-ms-wmv",
        "flv" => "video/x-flv",
        "webm" => "video/webm",
        "m4v" => "video/x-m4v",
        _ => return Err("Unsupported video format".to_string()),
    };

    // 读取文件内容
    match fs::read(&file_path) {
        Ok(file_data) => {
            // 编码为base64
            let base64_data = general_purpose::STANDARD.encode(&file_data);
            // 返回data URL格式
            Ok(format!("data:{};base64,{}", mime_type, base64_data))
        }
        Err(e) => Err(format!("Failed to read file: {}", e)),
    }
}

/// 检查文件是否存在
#[command]
pub async fn check_file_exists(file_path: String) -> Result<bool, String> {
    let path = Path::new(&file_path);
    Ok(path.exists())
}

/// 获取文件信息
#[command]
pub async fn get_file_info(file_path: String) -> Result<serde_json::Value, String> {
    let path = Path::new(&file_path);

    if !path.exists() {
        return Err("File does not exist".to_string());
    }

    match fs::metadata(&file_path) {
        Ok(metadata) => {
            let info = serde_json::json!({
                "exists": true,
                "size": metadata.len(),
                "is_file": metadata.is_file(),
                "is_dir": metadata.is_dir(),
                "modified": metadata.modified()
                    .map(|t| t.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs())
                    .unwrap_or(0)
            });
            Ok(info)
        }
        Err(e) => Err(format!("Failed to get file metadata: {}", e))
    }
}

/// 获取视频文件的blob URL（用于大文件）
#[command]
pub async fn get_video_blob_url(file_path: String) -> Result<String, String> {
    let path = Path::new(&file_path);

    // 检查文件是否存在
    if !path.exists() {
        return Err("File does not exist".to_string());
    }

    // 对于视频文件，我们返回文件路径，让前端使用convertFileSrc
    Ok(file_path)
}
