from __future__ import annotations

import os
import sys
from pathlib import Path

SOURCE_ROOT = Path(__file__).resolve().parent.parent
if str(SOURCE_ROOT) not in sys.path:
    sys.path.insert(0, str(SOURCE_ROOT))

from common.runtime_paths import PROJECT_ROOT, _runtime_base_dir, bundled_dir


def _has_huawei_worker_entry(path: Path) -> bool:
    return (
        (path / "main.py").exists()
        or (path / "main.pyc").exists()
    ) and (
        (path / "data.py").exists()
        or (path / "data.pyc").exists()
    )


def huawei_wwwroot_source_dir() -> str:
    """查找华为云旧后端源码快照目录，兼容源码运行、打包运行和旧下载目录。"""
    candidates = [
        PROJECT_ROOT / "HUAWEI" / "api",
        _runtime_base_dir() / "HUAWEI" / "api",
        Path(bundled_dir("autobuy_sources_v85")) / "huawei",
        PROJECT_ROOT / "autobuy_sources_v85" / "huawei",
        PROJECT_ROOT / "autobuy_sources_v57" / "huawei",
        Path(r"C:\Users\admin\Downloads\wwwroot_fze5a\wwwroot\backend\app\modules\huawei"),
    ]
    for path in candidates:
        if _has_huawei_worker_entry(path):
            return str(path)
    raise FileNotFoundError("Huawei autobuy source directory was not found.")


def run_huawei_wwwroot_worker() -> int:
    """运行华为云旧后端入口，供统一启动器和旧调用链继续复用。"""
    source_dir = huawei_wwwroot_source_dir()
    old_cwd = os.getcwd()
    sys.path.insert(0, source_dir)
    os.chdir(source_dir)
    try:
        import main as huawei_wwwroot_main  # type: ignore

        result = huawei_wwwroot_main.main()
        return int(result or 0)
    finally:
        os.chdir(old_cwd)


if __name__ == "__main__":
    raise SystemExit(run_huawei_wwwroot_worker())
