from __future__ import annotations

import sys
import os
from pathlib import Path


PROJECT_ROOT = Path(__file__).resolve().parents[1]
ASSETS_DIR = PROJECT_ROOT / "assets"
APP_DATA_DIR_NAME = "多云管理"


def _runtime_base_dir() -> Path:
    """返回源码运行或 PyInstaller 打包运行时的资源根目录。"""
    return Path(getattr(sys, "_MEIPASS", PROJECT_ROOT))


def portable_root_dir() -> Path:
    """返回便携包根目录；用于把日志、任务数据固定在 WaWaCloud/data。"""
    override = os.environ.get("WAWA_PORTABLE_ROOT", "").strip()
    if override:
        return Path(override)
    source_override = os.environ.get("WAWA_HOT_UPDATE_SOURCE_DIR", "").strip()
    if source_override:
        source_dir = Path(source_override).resolve()
        if source_dir.name.lower() == "source":
            return source_dir.parent
    if getattr(sys, "frozen", False):
        exe_dir = Path(sys.executable).resolve().parent
        if (exe_dir / "source").exists():
            return exe_dir
    if PROJECT_ROOT.name.lower() == "source":
        return PROJECT_ROOT.parent
    return PROJECT_ROOT


def resource_path(filename: str) -> str:
    """按项目结构查找资源文件，兼容源码运行和 exe 打包运行。"""
    base_dir = _runtime_base_dir()
    candidates = [
        base_dir / filename,
        base_dir / "assets" / filename,
        ASSETS_DIR / filename,
        PROJECT_ROOT / filename,
        PROJECT_ROOT / "HUAWEI" / "scripts" / filename,
        PROJECT_ROOT / "CTYUN" / filename,
        PROJECT_ROOT / "CTYUN" / "scripts" / filename,
        PROJECT_ROOT / "Volcengine" / "scripts" / filename,
    ]
    for path in candidates:
        if path.exists():
            return str(path)
    return str(ASSETS_DIR / filename)


def bundled_dir(dirname: str) -> str:
    """查找随程序一起携带的目录，优先兼容 PyInstaller 临时目录。"""
    base_dir = _runtime_base_dir()
    candidates = [
        base_dir / dirname,
        PROJECT_ROOT / dirname,
        PROJECT_ROOT / "sources" / dirname,
    ]
    for path in candidates:
        if path.exists():
            return str(path)
    return str(PROJECT_ROOT / dirname)


def app_data_root() -> Path:
    """返回软件运行数据根目录，所有云的日志和状态文件都从这里再分云存放。"""
    override = os.environ.get("WAWA_APP_DATA_DIR", "").strip()
    if override:
        root = Path(override)
    else:
        portable_data = portable_root_dir() / "data"
        root = portable_data if (portable_root_dir() / "source").exists() else Path.home() / "Documents" / APP_DATA_DIR_NAME
    root.mkdir(parents=True, exist_ok=True)
    return root


def cloud_data_dir(cloud_name: str) -> Path:
    """返回某个云的独立运行目录，避免华为云、天翼云、火山云互相混日志。"""
    safe_name = cloud_name.strip().replace("/", "_").replace("\\", "_") or "common"
    path = app_data_root() / safe_name
    path.mkdir(parents=True, exist_ok=True)
    return path


def cloud_log_dir(cloud_name: str) -> Path:
    """返回某个云的独立日志目录。"""
    path = cloud_data_dir(cloud_name) / "logs"
    path.mkdir(parents=True, exist_ok=True)
    return path


def cloud_runtime_dir(cloud_name: str) -> Path:
    """返回某个云的独立状态目录，用来保存 run_result、state、cleanup 等运行文件。"""
    path = cloud_data_dir(cloud_name) / "runtime"
    path.mkdir(parents=True, exist_ok=True)
    return path
