from __future__ import annotations

import os
import re
import sys
from pathlib import Path


APP_TITLE_VOLCENGINE = "\u706b\u5c71\u5f15\u64ce\u7ba1\u7406"
APP_VERSION_VOLCENGINE = "6.18.59"
ALLOW_PLAIN_SOURCE_ENV = "WAWA_ALLOW_VOLCENGINE_PLAIN_SOURCE"
VOLCENGINE_STANDALONE_LIMITED_ENV = "WAWA_VOLCENGINE_STANDALONE_LIMITED"
os.environ.setdefault("WAWA_SINGLE_VENDOR", "volc")
os.environ.setdefault(VOLCENGINE_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_volcengine_source_dir(path: Path) -> bool:
    return (
        (path / "main_volcengine.py").exists()
        and (path / "launcher" / "app.py").exists()
        and (path / "Volcengine" / "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_VOLCENGINE / "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_volcengine_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] == "--volc-worker":
    from Volcengine.source_runner import run_volc_wwwroot_worker

    raise SystemExit(run_volc_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_VOLCENGINE
    match = re.search(r'^APP_VERSION\s*=\s*[\'"]([^\'"]+)[\'"]', text, re.M)
    return match.group(1).strip() if match else APP_VERSION_VOLCENGINE


def run_self_test() -> None:
    from common.update_guard import VOLCENGINE_UPDATE_PACKAGE, _normalize_package_key
    from Volcengine.app import VolcEngineManagerApp, volcengine_standalone_limited_features
    from launcher import app as launcher_app

    assert APP_VERSION_VOLCENGINE == "6.18.59"
    assert _normalize_package_key("volcengine") == VOLCENGINE_UPDATE_PACKAGE
    assert launcher_app._normalize_single_vendor_key("huoshan") == "volc"
    assert volcengine_standalone_limited_features()
    saved_limited = os.environ.pop(VOLCENGINE_STANDALONE_LIMITED_ENV, None)
    saved_vendor = os.environ.get("WAWA_SINGLE_VENDOR")
    try:
        os.environ["WAWA_SINGLE_VENDOR"] = "volc"
        assert volcengine_standalone_limited_features()
        os.environ.pop("WAWA_SINGLE_VENDOR", None)
        assert not volcengine_standalone_limited_features()
    finally:
        if saved_limited is not None:
            os.environ[VOLCENGINE_STANDALONE_LIMITED_ENV] = saved_limited
        if saved_vendor is not None:
            os.environ["WAWA_SINGLE_VENDOR"] = saved_vendor
    limited_view = type(
        "LimitedVolcView",
        (),
        {
            "_standalone_limited_features": lambda self: True,
            "_customer_manage_eip_only": lambda self: False,
        },
    )()
    limited_items = VolcEngineManagerApp._manage_display_items(
        limited_view,
        [{"_kind": "ecs"}, {"_kind": "eip"}, {"_kind": "vpc"}],
    )
    assert [item["_kind"] for item in limited_items] == ["eip", "vpc"]
    customer_view = type(
        "CustomerVolcView",
        (),
        {
            "_standalone_limited_features": lambda self: True,
            "_customer_manage_eip_only": lambda self: True,
        },
    )()
    customer_items = VolcEngineManagerApp._manage_display_items(
        customer_view,
        [{"_kind": "ecs"}, {"_kind": "eip"}, {"_kind": "vpc"}, {"_kind": "network_interface"}],
    )
    assert [item["_kind"] for item in customer_items] == ["eip"]
    assert VolcEngineManagerApp is not None
    print("volcengine 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 VOLCENGINE_DOWNLOAD_PAGE_URL, VOLCENGINE_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_VOLCENGINE)
    if not launcher_app.show_startup_notice_window(
        app_title=APP_TITLE_VOLCENGINE,
        subtitle="\u706b\u5c71\u5f15\u64ce\u7ba1\u7406\u72ec\u7acb\u5206\u5305\uff0c\u4ec5\u5305\u542b\u706b\u5c71\u5f15\u64ce\u76f8\u5173\u529f\u80fd\u3002",
        version=APP_VERSION_VOLCENGINE,
        package_label="\u706b\u5c71\u5f15\u64ce\u72ec\u7acb\u5305",
        platform_label="\u706b\u5c71\u5f15\u64ce",
        logo_filename="logo_app_68.png",
        package_key=VOLCENGINE_UPDATE_PACKAGE,
        download_page_url=VOLCENGINE_DOWNLOAD_PAGE_URL,
    ):
        return
    app = launcher_app.MultiCloudManagerApp(single_vendor="volc", app_title=APP_TITLE_VOLCENGINE)
    app.mainloop()


if __name__ == "__main__":
    main()
