from __future__ import annotations

import os
import re
import sys
from pathlib import Path


APP_TITLE_HUAWEI = "华为云管理"
APP_VERSION_HUAWEI = "6.18.59"
ALLOW_PLAIN_SOURCE_ENV = "WAWA_ALLOW_HUAWEI_PLAIN_SOURCE"
HUAWEI_STANDALONE_LIMITED_ENV = "WAWA_HUAWEI_STANDALONE_LIMITED"
os.environ.setdefault("WAWA_SINGLE_VENDOR", "huawei")
os.environ.setdefault(HUAWEI_STANDALONE_LIMITED_ENV, "1")
os.environ.setdefault("WAWA_DIALOG_ICON_FILENAME", "app_dialog_icon.ico")
os.environ.setdefault("WAWA_DIALOG_LOGO_FILENAME", "logo_app_68.png")


def _desktop_dir() -> Path:
    try:
        desktop = Path.home() / "Desktop"
        if desktop.exists():
            return desktop
    except Exception:
        pass
    return Path.cwd()


def _running_from_frozen_exe() -> bool:
    return bool(getattr(sys, "frozen", False))


def _exe_dir() -> Path:
    try:
        if _running_from_frozen_exe():
            return Path(sys.executable).resolve().parent
    except OSError:
        pass
    return Path.cwd()


def _is_huawei_source_dir(path: Path) -> bool:
    return (
        (path / "main_huawei_shell.py").exists()
        and (path / "launcher" / "app.py").exists()
        and (path / "HUAWEI" / "app.py").exists()
        and (path / "common" / "shared.py").exists()
    )


def _hot_update_candidates() -> list[Path]:
    candidates: list[Path] = []
    frozen = _running_from_frozen_exe()
    allow_plain_source = os.environ.get(ALLOW_PLAIN_SOURCE_ENV, "").strip() == "1"
    env_source = os.environ.get("WAWA_HOT_UPDATE_SOURCE_DIR", "").strip()
    if env_source and (not frozen or allow_plain_source):
        candidates.append(Path(env_source))
    if not frozen:
        candidates.append(Path(__file__).resolve().parent)
    exe_dir = _exe_dir()
    candidates.append(exe_dir / "source")
    if not frozen or allow_plain_source:
        candidates.append(_desktop_dir() / APP_TITLE_HUAWEI / "source")
    return candidates


def _activate_hot_update_source() -> None:
    for candidate in _hot_update_candidates():
        try:
            source_dir = candidate.resolve()
        except OSError:
            continue
        if not _is_huawei_source_dir(source_dir):
            continue
        source_text = str(source_dir)
        if source_text not in sys.path:
            sys.path.insert(0, source_text)
        os.environ["WAWA_HOT_UPDATE_SOURCE_DIR"] = source_text
        if source_dir.name.lower() == "source":
            portable_root = source_dir.parent
            os.environ.setdefault("WAWA_PORTABLE_ROOT", str(portable_root))
            os.environ.setdefault("WAWA_APP_DATA_DIR", str(portable_root / "data"))
        try:
            os.chdir(source_text)
        except OSError:
            pass
        return


_activate_hot_update_source()

try:
    from common.package_metadata_fallbacks import ensure_package_metadata_fallbacks

    ensure_package_metadata_fallbacks()
except Exception:
    pass

try:
    from common.codec_fallbacks import ensure_idna_codec

    ensure_idna_codec()
except Exception:
    pass

if len(sys.argv) > 1 and sys.argv[1] == "--task-worker":
    from common.task_worker import main as task_worker_main

    raise SystemExit(task_worker_main(sys.argv[2:]))

if len(sys.argv) > 1 and sys.argv[1] == "--huawei-wwwroot-worker":
    from HUAWEI.source_runner import run_huawei_wwwroot_worker

    raise SystemExit(run_huawei_wwwroot_worker())


def _read_app_version() -> str:
    shared_path = Path(__file__).resolve().parent / "common" / "shared.py"
    try:
        text = shared_path.read_text(encoding="utf-8", errors="ignore")
    except Exception:
        return APP_VERSION_HUAWEI
    match = re.search(r'^APP_VERSION\s*=\s*[\'"]([^\'"]+)[\'"]', text, re.M)
    return match.group(1).strip() if match else APP_VERSION_HUAWEI


def run_self_test() -> None:
    from common.update_guard import HUAWEI_UPDATE_PACKAGE, _normalize_package_key
    from HUAWEI.app import HuaweiAutoBuyApp, huawei_standalone_limited_features
    from HUAWEI.cloud_client import HuaweiCloudClient
    from launcher import app as launcher_app

    assert _read_app_version() == APP_VERSION_HUAWEI
    assert _normalize_package_key("huawei") == HUAWEI_UPDATE_PACKAGE
    assert launcher_app._normalize_single_vendor_key("huaweicloud") == "huawei"
    assert huawei_standalone_limited_features()
    assert HuaweiAutoBuyApp is not None
    client = HuaweiCloudClient("test-ak", "test-sk", "test-domain")
    calls = []

    def fake_request(method, url, body=None, **kwargs):
        calls.append((method, url, kwargs))
        if url.endswith("/v3/auth/projects"):
            return 200, {"projects": [{"name": "cn-south-1", "id": "project-guangzhou"}]}, ""
        return 200, {"domains": [{"id": "test-domain"}]}, ""

    client.request = fake_request
    projects = client.warmup_region("cn-south-1")
    assert [item[1] for item in calls] == [
        "https://iam.cn-south-1.myhuaweicloud.com/v3/auth/domains",
        "https://iam.cn-south-1.myhuaweicloud.com/v3/auth/projects",
    ]
    assert calls[1][2]["use_domain_header"]
    assert projects == [{"name": "cn-south-1", "id": "project-guangzhou"}]
    print("huawei shell self-test ok")


def main() -> None:
    if "--self-test" in sys.argv:
        run_self_test()
        return
    from common.portable_runtime import ensure_portable_desktop_shortcut
    from common.process_utils import cleanup_stale_pyinstaller_dirs
    from common.ui_helpers import set_windows_app_user_model_id
    from common.update_guard import HUAWEI_DOWNLOAD_PAGE_URL, HUAWEI_UPDATE_PACKAGE
    from launcher import app as launcher_app

    cleanup_stale_pyinstaller_dirs()
    set_windows_app_user_model_id()
    ensure_portable_desktop_shortcut(APP_TITLE_HUAWEI)
    if not launcher_app.show_startup_notice_window(
        app_title=APP_TITLE_HUAWEI,
        subtitle="华为云管理独立分包，仅包含华为云相关功能。",
        version=APP_VERSION_HUAWEI,
        package_label="华为云独立包",
        platform_label="华为云",
        logo_filename="logo_app_68.png",
        package_key=HUAWEI_UPDATE_PACKAGE,
        download_page_url=HUAWEI_DOWNLOAD_PAGE_URL,
    ):
        return
    app = launcher_app.MultiCloudManagerApp(single_vendor="huawei", app_title=APP_TITLE_HUAWEI)
    app.mainloop()


if __name__ == "__main__":
    main()
