//! 路径计算集中管理
//!
//! 所有本地存储路径的计算逻辑统一放在此处，禁止在业务代码中硬编码路径。
//! 所有返回 PathBuf 的函数内部已做路径净化。
//!
//! 存储根目录为 app_local_data_dir，在应用启动时通过 init_app_data_dir 初始化。

use std::path::PathBuf;
use std::sync::OnceLock;
use tauri::{AppHandle, Manager};
use crate::storage::engine::{sanitize_id, StorageError};

static APP_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();

/// 初始化应用数据目录（在应用启动时调用一次）
pub fn init_app_data_dir(path: PathBuf) {
    let _ = APP_DATA_DIR.set(path);
}

/// 获取应用数据目录（crate 内部使用）
pub fn get_app_data_dir() -> Result<&'static PathBuf, StorageError> {
    APP_DATA_DIR.get()
        .ok_or_else(|| StorageError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "应用数据目录未初始化",
        )))
}

/// 获取项目根目录（所有项目的父目录）
/// {app_local_data_dir}/projects/
pub fn get_projects_root_dir() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    let path = base.join("projects");
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path)
}

/// 获取项目目录路径（不自动创建）
/// {app_local_data_dir}/projects/{project_id}/
pub fn get_project_dir_path(project_id: &str) -> Result<PathBuf, StorageError> {
    let safe_id = sanitize_id(project_id)?;
    let base = get_app_data_dir()?;
    Ok(base.join("projects").join(&safe_id))
}

/// 获取项目目录（自动创建）
/// {app_local_data_dir}/projects/{project_id}/
pub fn get_project_dir(project_id: &str) -> Result<PathBuf, StorageError> {
    let path = get_project_dir_path(project_id)?;
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path)
}

/// 获取项目内的 assets 目录
/// {app_local_data_dir}/projects/{project_id}/assets/
pub fn get_project_assets_dir(project_id: &str) -> Result<PathBuf, StorageError> {
    let path = get_project_dir(project_id)?;
    let assets = path.join("assets");
    crate::storage::engine::ensure_dir(&assets)?;
    Ok(assets)
}

/// 获取项目内的 videos 目录
/// {app_local_data_dir}/projects/{project_id}/videos/
pub fn get_project_videos_dir(project_id: &str) -> Result<PathBuf, StorageError> {
    let path = get_project_dir(project_id)?;
    let videos = path.join("videos");
    crate::storage::engine::ensure_dir(&videos)?;
    Ok(videos)
}

/// 获取项目成品目录
/// {app_local_data_dir}/projects/{project_id}/products/
pub fn get_project_products_dir(project_id: &str) -> Result<PathBuf, StorageError> {
    let safe_id = sanitize_id(project_id)?;
    let base = get_app_data_dir()?;
    let path = base.join("projects").join(&safe_id).join("products");
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path)
}

/// 获取私有音色素材库 JSON 路径
/// {app_local_data_dir}/voices.json
pub fn get_voices_json_path() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    Ok(base.join("voices.json"))
}

/// 获取应用配置路径
/// {app_local_data_dir}/config.json
pub fn get_app_config_json_path() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    Ok(base.join("config.json"))
}

/// 获取认证状态文件路径
/// {app_config_dir}/auth.json
pub fn get_auth_state_path(app: &AppHandle) -> Result<PathBuf, StorageError> {
    let path = app.path().app_config_dir()
        .map_err(|e| StorageError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("获取应用配置目录失败: {}", e),
        )))?;
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path.join("auth.json"))
}

/// 获取封面形象图片存储目录
/// {app_local_data_dir}/cover_avatars/
pub fn get_cover_avatars_dir() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    let path = base.join("cover_avatars");
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path)
}

/// 获取封面形象库 JSON 路径
/// {app_local_data_dir}/cover_avatars.json
pub fn get_cover_avatars_json_path() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    Ok(base.join("cover_avatars.json"))
}

/// 获取 BGM 缓存目录
/// {app_local_data_dir}/bgm_cache/
pub fn get_bgm_cache_dir() -> Result<PathBuf, StorageError> {
    let base = get_app_data_dir()?;
    let path = base.join("bgm_cache");
    crate::storage::engine::ensure_dir(&path)?;
    Ok(path)
}
