use std::{
    collections::BTreeSet,
    env, fs,
    path::{Path, PathBuf},
};

const STEAM_GAME_FOLDERS: &[&str] = &["Everquest F2P", "EverQuest"];
const DAYBREAK_GAME_FOLDERS: &[&str] = &["EverQuest", "Everquest", "EverQuest Legends"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CharacterLog {
    pub character: String,
    pub server: Option<String>,
    pub path: PathBuf,
    pub game_directory: PathBuf,
}

impl CharacterLog {
    pub fn display_name(&self) -> String {
        self.server.as_ref().map_or_else(
            || self.character.clone(),
            |server| format!("{} — {server}", self.character),
        )
    }
}

pub fn discover_character_logs(configured_game_directory: Option<&Path>) -> Vec<CharacterLog> {
    let mut game_directories = BTreeSet::new();
    if let Some(directory) = configured_game_directory {
        game_directories.insert(directory.to_path_buf());
    }
    game_directories.extend(default_game_directories());

    let mut logs = game_directories
        .into_iter()
        .flat_map(|directory| logs_in_game_directory(&directory))
        .collect::<Vec<_>>();
    logs.sort_by_key(|log| log.display_name());
    logs.dedup_by(|left, right| left.path == right.path);
    logs
}

pub fn logs_in_game_directory(game_directory: &Path) -> Vec<CharacterLog> {
    [game_directory.to_path_buf(), game_directory.join("Logs")]
        .into_iter()
        .flat_map(|directory| logs_in_directory(&directory, game_directory))
        .collect()
}

fn logs_in_directory(directory: &Path, game_directory: &Path) -> Vec<CharacterLog> {
    let Ok(entries) = fs::read_dir(directory) else {
        return Vec::new();
    };
    entries
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let path = entry.path();
            path.is_file()
                .then(|| character_log_from_path(path, game_directory.to_path_buf()))
                .flatten()
        })
        .collect()
}

fn character_log_from_path(path: PathBuf, game_directory: PathBuf) -> Option<CharacterLog> {
    let file_name = path.file_name()?.to_string_lossy().into_owned();
    let stem = file_name.strip_suffix(".txt")?;
    let stem = stem
        .strip_prefix("eqlog_")
        .or_else(|| stem.strip_prefix("EQLOG_"))?;
    if stem.is_empty() {
        return None;
    }
    let (character, server) = stem
        .split_once('_')
        .map_or((stem, None), |(character, server)| {
            (character, Some(server))
        });
    (!character.is_empty()).then(|| CharacterLog {
        character: character.to_owned(),
        server: server
            .filter(|server| !server.is_empty())
            .map(str::to_owned),
        path,
        game_directory,
    })
}

fn default_game_directories() -> BTreeSet<PathBuf> {
    let mut directories = BTreeSet::new();
    for steam_library in steam_libraries() {
        for game_folder in STEAM_GAME_FOLDERS {
            directories.insert(steam_library.join("steamapps/common").join(game_folder));
        }
    }

    if cfg!(target_os = "windows") {
        for public_directory in windows_public_directories() {
            for game_folder in DAYBREAK_GAME_FOLDERS {
                directories.insert(
                    public_directory
                        .join("Daybreak Game Company/Installed Games")
                        .join(game_folder),
                );
            }
        }
        directories.insert(PathBuf::from(r"C:\EverQuest"));
        directories.insert(PathBuf::from(r"C:\Program Files\EverQuest"));
        directories.insert(PathBuf::from(r"C:\Program Files (x86)\EverQuest"));
        for game_folder in DAYBREAK_GAME_FOLDERS {
            directories.insert(
                PathBuf::from(r"C:\Users\Public\Daybreak Game Company\Installed Games")
                    .join(game_folder),
            );
        }
    }
    directories
}

fn windows_public_directories() -> Vec<PathBuf> {
    let mut directories = vec![PathBuf::from(r"C:\Users\Public")];
    if let Some(directory) = env::var_os("PUBLIC") {
        directories.push(PathBuf::from(directory));
    }
    directories
}

fn steam_libraries() -> BTreeSet<PathBuf> {
    let mut libraries = BTreeSet::new();
    let mut steam_roots = BTreeSet::new();

    for variable in ["PROGRAMFILES(X86)", "PROGRAMFILES", "USERPROFILE"] {
        if let Some(value) = env::var_os(variable) {
            steam_roots.insert(PathBuf::from(value).join("Steam"));
        }
    }
    if let Some(home) = dirs::home_dir() {
        steam_roots.extend([
            home.join(".steam/steam"),
            home.join(".local/share/Steam"),
            home.join(".var/app/com.valvesoftware.Steam/.local/share/Steam"),
        ]);
    }
    if cfg!(target_os = "windows") {
        steam_roots.extend([
            PathBuf::from(r"C:\Program Files (x86)\Steam"),
            PathBuf::from(r"C:\Program Files\Steam"),
        ]);
    }

    for steam_root in steam_roots {
        libraries.insert(steam_root.clone());
        if let Ok(contents) = fs::read_to_string(steam_root.join("steamapps/libraryfolders.vdf")) {
            libraries.extend(steam_library_paths_from_vdf(&contents));
        }
    }
    libraries
}

fn steam_library_paths_from_vdf(contents: &str) -> Vec<PathBuf> {
    contents
        .lines()
        .filter_map(|line| {
            let quoted = line.split('"').skip(1).step_by(2).collect::<Vec<_>>();
            (quoted.first() == Some(&"path") && quoted.get(1).is_some())
                .then(|| PathBuf::from(quoted[1].replace(r"\\", r"\")))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn finds_character_logs_in_the_game_logs_directory() {
        let temporary = tempdir().unwrap();
        let game_directory = temporary.path().join("EverQuest");
        let logs_directory = game_directory.join("Logs");
        fs::create_dir_all(&logs_directory).unwrap();
        fs::write(logs_directory.join("eqlog_Pleb_oggok.txt"), "").unwrap();
        fs::write(game_directory.join("eqlog_Lucy_tunare.txt"), "").unwrap();
        fs::write(game_directory.join("notes.txt"), "").unwrap();

        let logs = logs_in_game_directory(&game_directory);
        assert_eq!(logs.len(), 2);
        assert!(logs.iter().any(|log| log.display_name() == "Pleb — oggok"));
        assert!(logs.iter().any(|log| log.display_name() == "Lucy — tunare"));
    }

    #[test]
    fn reads_steam_library_paths() {
        let contents = r#"
"libraryfolders"
{
    "0"
    {
        "path" "D:\\SteamLibrary"
    }
}
"#;
        assert_eq!(
            steam_library_paths_from_vdf(contents),
            vec![PathBuf::from(r"D:\SteamLibrary")]
        );
    }
}
