import os
import json
import time
import threading
from datetime import datetime, timedelta, timezone

try:
    from zoneinfo import ZoneInfo
    CAIRO_TZ = ZoneInfo("Africa/Cairo")
except Exception:
    CAIRO_TZ = timezone(timedelta(hours=2))

try:
    import fcntl as _fcntl
except ImportError:
    _fcntl = None

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(BASE_DIR, "config.json")
DB_FILE = os.path.join(BASE_DIR, "bot_db.json")
LOCK_FILE = os.path.join(BASE_DIR, ".bot_db.lock")

_thread_lock = threading.Lock()


def egypt_now():
    return datetime.now(CAIRO_TZ)


def load_config():
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            pass
    return {}


def save_config(cfg):
    tmp = f"{CONFIG_FILE}.{os.getpid()}.tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)
    os.replace(tmp, CONFIG_FILE)


class _DBLock:
    def __init__(self):
        self.fd = None

    def __enter__(self):
        _thread_lock.acquire()
        if _fcntl is not None:
            self.fd = open(LOCK_FILE, "a+")
            _fcntl.flock(self.fd, _fcntl.LOCK_EX)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if _fcntl is not None and self.fd is not None:
            try:
                _fcntl.flock(self.fd, _fcntl.LOCK_UN)
                self.fd.close()
            except Exception:
                pass
            self.fd = None
        _thread_lock.release()


def _default_db():
    return {
        "users": {},
        "orders": [],
        "deposits": [],
        "tickets": {},
        "announced_products": {}
    }


def load_db():
    with _DBLock():
        if os.path.exists(DB_FILE):
            try:
                with open(DB_FILE, "r", encoding="utf-8") as f:
                    data = json.load(f)
                if isinstance(data, dict):
                    base = _default_db()
                    base.update(data)
                    return base
            except Exception:
                pass
        return _default_db()


def update_db(mutator_fn):
    """Atomic read-modify-write under cross-process lock."""
    with _DBLock():
        db = _default_db()
        if os.path.exists(DB_FILE):
            try:
                with open(DB_FILE, "r", encoding="utf-8") as f:
                    raw = json.load(f)
                if isinstance(raw, dict):
                    db.update(raw)
            except Exception:
                pass

        result = mutator_fn(db)

        tmp = f"{DB_FILE}.{os.getpid()}.{threading.get_ident()}.tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(db, f, ensure_ascii=False, indent=2)
        os.replace(tmp, DB_FILE)
        return result


def get_vip_tier(total_spent):
    spent = float(total_spent or 0)
    if spent >= 250:
        return "💎 Diamond VIP"
    if spent >= 100:
        return "👑 Gold VIP"
    if spent >= 25:
        return "🥈 Silver Member"
    return "⚡ Starter Member"


def ensure_user(db, tg_user):
    uid = str(tg_user.get("id"))
    users = db.setdefault("users", {})
    uname = tg_user.get("username") or ""
    fname = tg_user.get("first_name") or "User"
    now_str = egypt_now().strftime("%Y-%m-%d %I:%M %p")
    if uid not in users:
        users[uid] = {
            "id": uid,
            "username": uname,
            "first_name": fname,
            "balance": 0.0,
            "total_spent": 0.0,
            "total_orders": 0,
            "joined_at": now_str,
            "last_seen": now_str,
            "state": None,
            "state_data": {}
        }
    else:
        users[uid]["username"] = uname or users[uid].get("username", "")
        users[uid]["first_name"] = fname or users[uid].get("first_name", "User")
        users[uid]["last_seen"] = now_str
    return users[uid]
