#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Entry point đóng gói (PyInstaller).
Chuyển working directory về thư mục app / _MEIPASS data.
"""
from __future__ import annotations

import os
import sys


def _app_dir() -> str:
    if getattr(sys, "frozen", False):
        # PyInstaller: exe/app nằm cạnh thư mục data người dùng
        return os.path.dirname(os.path.abspath(sys.executable))
    return os.path.dirname(os.path.abspath(__file__))


def _bundle_dir() -> str:
    """Tài nguyên đóng gói (read-only) khi frozen."""
    if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
        return sys._MEIPASS  # type: ignore[attr-defined]
    return _app_dir()


def main():
    app_dir = _app_dir()
    bundle = _bundle_dir()
    # Dữ liệu người dùng (json, cookie…) luôn cạnh executable / thư mục project
    os.chdir(app_dir)
    # Cho import module phụ (auth, geo, verify…)
    if bundle not in sys.path:
        sys.path.insert(0, bundle)
    if app_dir not in sys.path:
        sys.path.insert(0, app_dir)

    # Copy file mẫu lần đầu nếu thiếu
    _ensure_user_files(app_dir, bundle)

    # Playwright: trỏ browser về path đã cài (nếu có)
    _setup_playwright_env(app_dir)

    import fb_auto_tool_v9  # noqa: F401

    # Chạy main của tool
    if hasattr(fb_auto_tool_v9, "main"):
        fb_auto_tool_v9.main()
    else:
        # fallback: file chạy trực tiếp block if __name__
        import runpy

        runpy.run_module("fb_auto_tool_v9", run_name="__main__")


def _ensure_user_files(app_dir: str, bundle: str):
    """Tạo file/thư mục dữ liệu nếu chưa có."""
    defaults = {
        "proxies.txt": "# IP:PORT:USER:PASS\n",
        "import_accounts.txt": "# uid|pass|2fa|email|cookie\n",
        "app_settings_v10.json": '{\n  "theme": "light"\n}\n',
    }
    for name, content in defaults.items():
        path = os.path.join(app_dir, name)
        if not os.path.exists(path):
            try:
                with open(path, "w", encoding="utf-8") as f:
                    f.write(content)
            except Exception:
                pass

    # copy vietnamese_names nếu thiếu
    names_dst = os.path.join(app_dir, "vietnamese_names.txt")
    names_src = os.path.join(bundle, "vietnamese_names.txt")
    if not os.path.exists(names_dst) and os.path.exists(names_src):
        try:
            import shutil

            shutil.copy2(names_src, names_dst)
        except Exception:
            pass

    for d in ("avatars", "checkpoint_verify", "website"):
        p = os.path.join(app_dir, d)
        try:
            os.makedirs(p, exist_ok=True)
        except Exception:
            pass
    # copy website tĩnh nếu trống
    web_src = os.path.join(bundle, "website")
    web_dst = os.path.join(app_dir, "website")
    if os.path.isdir(web_src) and not os.listdir(web_dst):
        try:
            import shutil

            for root, _, files in os.walk(web_src):
                rel = os.path.relpath(root, web_src)
                target_root = web_dst if rel == "." else os.path.join(web_dst, rel)
                os.makedirs(target_root, exist_ok=True)
                for fn in files:
                    shutil.copy2(os.path.join(root, fn), os.path.join(target_root, fn))
        except Exception:
            pass


def _setup_playwright_env(app_dir: str):
    """Dùng browser Playwright cài cạnh app nếu có."""
    local_browsers = os.path.join(app_dir, "ms-playwright")
    if os.path.isdir(local_browsers):
        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = local_browsers
    # home user fallback
    home_pw = os.path.expanduser("~/Library/Caches/ms-playwright")
    if sys.platform.startswith("win"):
        home_pw = os.path.join(os.environ.get("LOCALAPPDATA", ""), "ms-playwright")
    elif sys.platform.startswith("linux"):
        home_pw = os.path.expanduser("~/.cache/ms-playwright")
    if not os.environ.get("PLAYWRIGHT_BROWSERS_PATH") and os.path.isdir(home_pw):
        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = home_pw


if __name__ == "__main__":
    main()
