from __future__ import annotations

import os
import sys
from pathlib import Path

from common.runtime_paths import PROJECT_ROOT, _runtime_base_dir, bundled_dir


def volc_wwwroot_source_root() -> str:
    """查找火山云旧后端源码根目录，返回包含 volcengine 包的上级目录。"""
    candidates = [
        PROJECT_ROOT / "Volcengine" / "api",
        _runtime_base_dir() / "Volcengine" / "api",
        Path(bundled_dir("autobuy_sources_v85")),
        PROJECT_ROOT / "autobuy_sources_v85",
        Path(r"C:\Users\admin\Downloads\wwwroot_fze5a\wwwroot\backend\app\modules"),
    ]
    for path in candidates:
        module_dir = path / "volcengine"
        if (module_dir / "main.py").exists() and (module_dir / "data.py").exists():
            return str(path)
    raise FileNotFoundError("Volcengine autobuy source directory was not found.")


def run_volc_wwwroot_worker() -> int:
    """运行火山云旧后端入口，运行前清理同名模块缓存避免串到旧路径。"""
    source_root = volc_wwwroot_source_root()
    module_dir = os.path.join(source_root, "volcengine")
    old_cwd = os.getcwd()
    old_path = list(sys.path)
    for module_name in list(sys.modules):
        if module_name == "volcengine" or module_name.startswith("volcengine."):
            sys.modules.pop(module_name, None)
    sys.path.insert(0, source_root)
    os.chdir(module_dir)
    try:
        import importlib

        volc_main = importlib.import_module("volcengine.main")
        result = volc_main.main()
        return int(result or 0)
    finally:
        os.chdir(old_cwd)
        sys.path[:] = old_path
