use anyhow::Result;
use std::fs;
use std::path::{Path, PathBuf};

pub struct FileManager {
    base_dir: PathBuf,
}

impl FileManager {
    pub fn new(base_dir: PathBuf) -> Self {
        Self { base_dir }
    }

    pub fn get_json_path(&self, uuid: &str, suffix: &str) -> PathBuf {
        self.base_dir.join(format!("{}.{}.json", uuid, suffix))
    }

    pub fn save_json(&self, uuid: &str, suffix: &str, content: &str) -> Result<PathBuf> {
        let path = self.get_json_path(uuid, suffix);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&path, content)?;
        Ok(path)
    }

    pub fn load_json(&self, uuid: &str, suffix: &str) -> Result<String> {
        let path = self.get_json_path(uuid, suffix);
        Ok(fs::read_to_string(path)?)
    }

    pub fn exists(&self, uuid: &str, suffix: &str) -> bool {
        self.get_json_path(uuid, suffix).exists()
    }

    pub fn list_video_files(dir: &Path) -> Result<Vec<PathBuf>> {
        let mut videos = Vec::new();

        if !dir.exists() {
            return Ok(videos);
        }

        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if let Some(ext) = path.extension() {
                let ext = ext.to_string_lossy().to_lowercase();
                if matches!(ext.as_str(), "mp4" | "mkv" | "avi" | "mov" | "webm" | "m4v") {
                    videos.push(path);
                }
            }
        }

        Ok(videos)
    }
}
