from __future__ import annotations

import os
import re
import sys
from pathlib import Path


APP_TITLE_CTYUN = "天翼云管理"
APP_VERSION_CTYUN = "6.18.59"
ALLOW_PLAIN_SOURCE_ENV = "WAWA_ALLOW_CTYUN_PLAIN_SOURCE"
CTYUN_STANDALONE_LIMITED_ENV = "WAWA_CTYUN_STANDALONE_LIMITED"
os.environ.setdefault("WAWA_SINGLE_VENDOR", "ctyun")
os.environ.setdefault(CTYUN_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_ctyun_source_dir(path: Path) -> bool:
    return (
        (path / "main_ctyun.py").exists()
        and (path / "launcher" / "app.py").exists()
        and (path / "CTYUN" / "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_CTYUN / "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_ctyun_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] == "--ctyun-worker":
    from CTYUN.app import worker_main

    raise SystemExit(worker_main())


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


def run_self_test() -> None:
    from CTYUN.app import WorkflowGui, ctyun_standalone_limited_features
    from common.update_guard import CTYUN_UPDATE_PACKAGE, _normalize_package_key
    from launcher import app as launcher_app

    assert APP_VERSION_CTYUN == "6.18.59"
    assert _normalize_package_key("tianyi") == CTYUN_UPDATE_PACKAGE
    assert launcher_app._normalize_single_vendor_key("tianyi") == "ctyun"
    assert ctyun_standalone_limited_features()
    limited_view = type(
        "LimitedCTYUNView",
        (),
        {
            "_standalone_limited_features": lambda self: True,
            "_customer_cleanup_limited_features": lambda self: False,
            "_cleanup_cloud_server_limited_features": WorkflowGui._cleanup_cloud_server_limited_features,
        },
    )()
    limited_items = WorkflowGui._cleanup_display_items(
        limited_view,
        [{"type": "ECS"}, {"type": "EIP"}, {"type": "VPC"}],
    )
    assert [item["type"] for item in limited_items] == ["EIP", "VPC"]
    customer_view = type(
        "CustomerLimitedCTYUNView",
        (),
        {
            "_standalone_limited_features": lambda self: False,
            "_customer_cleanup_limited_features": lambda self: True,
            "_cleanup_cloud_server_limited_features": WorkflowGui._cleanup_cloud_server_limited_features,
            "_is_active_cleanup_ecs_item": lambda self, item: str(item.get("type") or "") == "ECS",
            "dynamic_region_labels": {},
            "account_resource_items": [
                {"type": "ECS"},
                {"type": "EIP"},
                {"type": "HAVIP_EIP"},
                {"type": "HAVIP"},
                {"type": "VPC"},
                {"type": "SECURITY_GROUP"},
            ],
            "cleanup_items": [{"type": "EIP"}, {"type": "HAVIP_EIP"}],
        },
    )()
    customer_items = WorkflowGui._cleanup_display_items(
        customer_view,
        customer_view.account_resource_items,
    )
    assert [item["type"] for item in customer_items] == ["EIP", "HAVIP_EIP"]
    assert WorkflowGui._cleanup_region_summary(customer_view, customer_items) == "EIP:2"
    assert [item["type"] for item in WorkflowGui._account_resources_for_purchase(customer_view)] == [
        "ECS",
        "EIP",
        "HAVIP_EIP",
        "HAVIP",
        "VPC",
        "SECURITY_GROUP",
    ]
    assert "ECS:1" in WorkflowGui._region_option_label(customer_view, "wuhu2", {"ECS": 1, "EIP": 1})
    print("ctyun 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 CTYUN_DOWNLOAD_PAGE_URL, CTYUN_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_CTYUN)
    if not launcher_app.show_startup_notice_window(
        app_title=APP_TITLE_CTYUN,
        subtitle="天翼云管理独立分包，仅包含天翼云相关功能。",
        version=APP_VERSION_CTYUN,
        package_label="天翼云独立包",
        platform_label="天翼云",
        logo_filename="logo_app_68.png",
        package_key=CTYUN_UPDATE_PACKAGE,
        download_page_url=CTYUN_DOWNLOAD_PAGE_URL,
    ):
        return
    app = launcher_app.MultiCloudManagerApp(single_vendor="ctyun", app_title=APP_TITLE_CTYUN)
    app.mainloop()


if __name__ == "__main__":
    main()
