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19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""bot_state.py — Shared state, locks, TG helpers, activity tracking,
bans, maintenance, admin auth, quota, flood, dedup, cache GC.

This module has NO imports from bot.py.
The handler file (bot.py) imports from here and re-exports.
"""
import logging
import threading
import time
from collections import deque, Counter

import httpx

from config import (
    TELEGRAM_API, OWNER_IDS, FORCE_JOIN_CHANNEL,
    MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL,
    FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC,
    DAILY_QUOTA, DAILY_QUOTA_ADMIN,
    LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX,
    ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL, SEARCH_CACHE_TTL,
)
from engine import esc

log = logging.getLogger("bot_state")

# ══════════════════════════════════════════════════════════════════
# STATE
# ══════════════════════════════════════════════════════════════════
ACTIVITY_LOG = deque(maxlen=ACTIVITY_LOG_MAX)
ACTIVE_USERS = {}
UNIQUE_USERS = {}
PHONE_COUNTS = Counter()
PEAK_CONCURRENT = 0
_activity_lock = threading.Lock()

_admin_lock = threading.Lock()
_admin_sessions = {}
_admin_states = {}

BANNED_USERS = set()
BAN_REASONS = {}
MAINTENANCE_MODE = False
MAINTENANCE_REASON = ""
_state_lock = threading.Lock()

USER_HISTORY = {}
SEARCH_CACHE = {}
SEARCH_CACHE_LOCK = threading.Lock()
USER_LAST = {}
STATS = {"queries": 0, "timeouts": 0, "errors": 0, "backup_sent": 0,
         "started": time.time()}

_member_cache = {}
_member_lock = threading.Lock()
_pending_query = {}
_pending_lock = threading.Lock()
_user_daily = {}
_quota_lock = threading.Lock()
_user_msg_times = {}
_muted_until = {}
_flood_lock = threading.Lock()
_seen_updates = {}
_seen_updates_lock = threading.Lock()

# ══════════════════════════════════════════════════════════════════
# TG HELPERS
# ══════════════════════════════════════════════════════════════════
async def tg(method, payload, timeout=30):
    try:
        async with httpx.AsyncClient(timeout=timeout) as cli:
            r = await cli.post(f"{TELEGRAM_API}/{method}", json=payload)
            return r.json()
    except Exception as e:
        log.error(f"tg({method}): {e!r}")
        return {"ok": False, "error": str(e)}


async def send(chat_id, text, **kw):
    kw.setdefault("parse_mode", "HTML")
    kw.setdefault("disable_web_page_preview", True)
    kw = {k: v for k, v in kw.items() if v is not None}
    try:
        res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **kw})
        if res.get("ok"):
            return res["result"]["message_id"]
        log.warning(f"sendMessage failed: {res}")
    except Exception as e:
        log.error(f"send error: {e!r}")
    return None


async def edit(chat_id, message_id, text, **kw):
    kw.setdefault("parse_mode", "HTML")
    kw.setdefault("disable_web_page_preview", True)
    kw = {k: v for k, v in kw.items() if v is not None}
    try:
        res = await tg("editMessageText",
                       {"chat_id": chat_id, "message_id": message_id,
                        "text": text, **kw})
        if not res.get("ok") and "message is not modified" not in str(res):
            log.warning(f"editMessageText failed: {res}")
    except Exception as e:
        log.error(f"edit error: {e!r}")


async def send_document(chat_id, filename, content, caption=""):
    try:
        files = {"document": (filename, content, "application/octet-stream")}
        data = {"chat_id": str(chat_id)}
        if caption:
            data["caption"] = caption[:1024]
        async with httpx.AsyncClient(timeout=60) as cli:
            r = await cli.post(f"{TELEGRAM_API}/sendDocument",
                               data=data, files=files)
            res = r.json()
            if not res.get("ok"):
                log.warning(f"sendDocument failed: {res}")
            return res
    except Exception as e:
        log.error(f"sendDocument error: {e!r}")
        return {"ok": False}

# ══════════════════════════════════════════════════════════════════
# SMALL HELPERS
# ══════════════════════════════════════════════════════════════════
def _short_user(user_id, user=None):
    info = UNIQUE_USERS.get(user_id) or {}
    username = (user or {}).get("username") or info.get("username")
    first = (user or {}).get("first_name") or info.get("first_name")
    if username:
        return f"@{username} ({user_id})"
    if first:
        return f"{first} ({user_id})"
    return f"({user_id})"


def _fmt_ts(ts):
    return time.strftime("%H:%M:%S", time.localtime(ts))


def _today_utc():
    return time.strftime("%Y-%m-%d", time.gmtime())

# ══════════════════════════════════════════════════════════════════
# UPDATE DEDUP
# ══════════════════════════════════════════════════════════════════
def is_duplicate_update(update_id):
    if not update_id:
        return False
    now = time.time()
    with _seen_updates_lock:
        if len(_seen_updates) > 2000:
            cutoff = now - 600
            for k in [k for k, v in _seen_updates.items() if v < cutoff]:
                del _seen_updates[k]
        if update_id in _seen_updates:
            return True
        _seen_updates[update_id] = now
        return False

# ══════════════════════════════════════════════════════════════════
# FORCE-JOIN
# ══════════════════════════════════════════════════════════════════
async def _is_channel_member(user_id):
    if not FORCE_JOIN_CHANNEL:
        return True
    now = time.time()
    with _member_lock:
        c = _member_cache.get(user_id)
        if c and now - c[1] < MEMBERSHIP_CACHE_TTL:
            return c[0]
    is_member = False
    try:
        res = await tg("getChatMember",
                       {"chat_id": FORCE_JOIN_CHANNEL, "user_id": user_id},
                       timeout=10)
        if res.get("ok"):
            status = (res.get("result") or {}).get("status", "")
            is_member = status in ("member", "administrator", "creator")
    except Exception as e:
        log.warning(f"[membership] {e!r}")
    with _member_lock:
        _member_cache[user_id] = (is_member, now)
    return is_member


def _join_url():
    if not FORCE_JOIN_CHANNEL:
        return ""
    if FORCE_JOIN_CHANNEL.startswith("http"):
        return FORCE_JOIN_CHANNEL
    if FORCE_JOIN_CHANNEL.startswith("@"):
        return f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}"
    return "https://t.me/"


async def check_force_join(chat_id, user, text):
    if not FORCE_JOIN_CHANNEL:
        return True
    uid = user.get("id")
    if not uid:
        return True
    if uid in OWNER_IDS:
        return True
    if _is_admin_session(uid):
        return True
    if text.startswith(("/start", "/help", "/myid", "/whoami",
                        "/ping", "/info", "/status")):
        return True
    if await _is_channel_member(uid):
        return True
    with _pending_lock:
        _pending_query[uid] = (text, chat_id, time.time())
    url = _join_url()
    await send(chat_id,
        "🔒 <b>Join required</b>\n\n"
        "To use this bot, please join our channel first.\n\n"
        f"👉 {esc(url)}\n\nAfter joining, tap <b>✅ I Joined</b> below.",
        reply_markup={"inline_keyboard": [
            [{"text": "📢 Join Channel", "url": url}],
            [{"text": "✅ I Joined", "callback_data": "join:check"}],
        ]})
    _log_activity(user, "force_join_block", text[:40], "blocked", "not a member")
    return False

# ══════════════════════════════════════════════════════════════════
# QUOTA
# ══════════════════════════════════════════════════════════════════
def _is_unlimited(user_id):
    return user_id in OWNER_IDS or _is_admin_session(user_id)


def check_quota(user_id):
    if _is_unlimited(user_id):
        return True, DAILY_QUOTA_ADMIN
    today = _today_utc()
    with _quota_lock:
        e = _user_daily.get(user_id)
        if not e or e[0] != today:
            _user_daily[user_id] = (today, 0)
            return True, DAILY_QUOTA
        if e[1] >= DAILY_QUOTA:
            return False, 0
        return True, DAILY_QUOTA - e[1]


def incr_quota(user_id):
    if _is_unlimited(user_id):
        return
    today = _today_utc()
    with _quota_lock:
        e = _user_daily.get(user_id)
        if not e or e[0] != today:
            _user_daily[user_id] = (today, 1)
        else:
            _user_daily[user_id] = (today, e[1] + 1)

# ══════════════════════════════════════════════════════════════════
# FLOOD
# ══════════════════════════════════════════════════════════════════
def check_flood(user_id):
    now = time.time()
    with _flood_lock:
        until = _muted_until.get(user_id, 0)
        if until > now:
            return int(until - now)
        dq = _user_msg_times.setdefault(user_id, deque(maxlen=FLOOD_MAX))
        dq.append(now)
        if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW:
            _muted_until[user_id] = now + FLOOD_MUTE_SEC
            return FLOOD_MUTE_SEC
    return None

# ══════════════════════════════════════════════════════════════════
# ACTIVITY
# ══════════════════════════════════════════════════════════════════
def _log_activity(user, action, input_val, reply_type, summary="",
                  elapsed_ms=0, source=""):
    if not user or "id" not in user:
        return
    now = time.time()
    user_id = user["id"]
    with _activity_lock:
        info = UNIQUE_USERS.setdefault(user_id, {
            "username": None, "first_name": None, "last_name": None,
            "count": 0, "first_seen": now, "last_seen": now,
        })
        if user.get("username"):
            info["username"] = user["username"]
        if user.get("first_name"):
            info["first_name"] = user["first_name"]
        if user.get("last_name"):
            info["last_name"] = user["last_name"]
        info["count"] += 1
        info["last_seen"] = now
        ACTIVE_USERS[user_id] = now
        if (action == "search" and isinstance(input_val, str)
                and input_val.isdigit() and len(input_val) == 10):
            PHONE_COUNTS[input_val] += 1
        ACTIVITY_LOG.append({
            "ts": now, "user_id": user_id,
            "username": user.get("username"),
            "first_name": user.get("first_name"),
            "action": action, "input": (input_val or "")[:80],
            "reply_type": reply_type, "summary": (summary or "")[:150],
            "elapsed_ms": int(elapsed_ms), "source": source,
        })


def _get_live_users():
    cutoff = time.time() - LIVE_WINDOW
    with _activity_lock:
        live = [(uid, ts) for uid, ts in ACTIVE_USERS.items() if ts >= cutoff]
    live.sort(key=lambda x: -x[1])
    return live


def _get_stats():
    now = time.time()
    today_start = now - (now % 86400)
    with _activity_lock:
        today_users = set()
        today_searches = 0
        total_searches = 0
        for e in ACTIVITY_LOG:
            if e["action"] == "search":
                total_searches += 1
                if e["ts"] >= today_start:
                    today_searches += 1
                    today_users.add(e["user_id"])
        return {
            "unique_users": len(UNIQUE_USERS),
            "live_users": sum(1 for ts in ACTIVE_USERS.values()
                              if ts >= now - LIVE_WINDOW),
            "today_users": len(today_users),
            "today_searches": today_searches,
            "total_searches": total_searches,
            "peak_concurrent": PEAK_CONCURRENT,
            "total_log_entries": len(ACTIVITY_LOG),
            "banned_count": len(BANNED_USERS),
            "maintenance": MAINTENANCE_MODE,
            "cached_searches": len(SEARCH_CACHE),
            "backup_sent": STATS["backup_sent"],
        }


def _add_to_history(user_id, phone, count, elapsed, source):
    if user_id is None:
        return
    with _activity_lock:
        h = USER_HISTORY.setdefault(user_id, deque(maxlen=HISTORY_LEN))
        h.appendleft({"phone": phone, "ts": time.time(), "count": count,
                      "elapsed": elapsed, "source": source})


def _avg_latency_today():
    now = time.time()
    today_start = now - (now % 86400)
    with _activity_lock:
        vals = [e["elapsed_ms"] for e in ACTIVITY_LOG
                if e["action"] == "search" and e["ts"] >= today_start
                and e["elapsed_ms"] > 0]
    return (sum(vals) / len(vals)) / 1000.0 if vals else 0.0

# ══════════════════════════════════════════════════════════════════
# BAN / MAINTENANCE
# ══════════════════════════════════════════════════════════════════
def _is_banned(user_id):
    with _state_lock:
        return user_id in BANNED_USERS


def _ban_user(user_id, reason=""):
    with _state_lock:
        BANNED_USERS.add(user_id)
        BAN_REASONS[user_id] = reason


def _unban_user(user_id):
    with _state_lock:
        if user_id in BANNED_USERS:
            BANNED_USERS.discard(user_id)
            BAN_REASONS.pop(user_id, None)
            return True
        return False


def _get_maintenance():
    with _state_lock:
        return MAINTENANCE_MODE, MAINTENANCE_REASON


def _set_maintenance(on, reason=""):
    global MAINTENANCE_MODE, MAINTENANCE_REASON
    with _state_lock:
        MAINTENANCE_MODE = on
        MAINTENANCE_REASON = reason if on else ""

# ══════════════════════════════════════════════════════════════════
# ADMIN AUTH
# ══════════════════════════════════════════════════════════════════
def _is_admin_session(user_id):
    if user_id is None:
        return False
    with _admin_lock:
        exp = _admin_sessions.get(user_id)
        if exp is None:
            return False
        if time.time() > exp:
            _admin_sessions.pop(user_id, None)
            return False
        return True


def _grant_admin(user_id):
    with _admin_lock:
        _admin_sessions[user_id] = time.time() + ADMIN_SESSION_TTL


def _revoke_admin(user_id):
    with _admin_lock:
        _admin_sessions.pop(user_id, None)


def _admin_state_get(user_id):
    with _admin_lock:
        e = _admin_states.get(user_id)
        if e is None:
            return None
        state, set_at = e
        if time.time() - set_at > ADMIN_PROMPT_TTL:
            _admin_states.pop(user_id, None)
            return None
        return state


def _admin_state_set(user_id, state):
    with _admin_lock:
        _admin_states[user_id] = (state, time.time())


def _admin_state_clear(user_id):
    with _admin_lock:
        _admin_states.pop(user_id, None)

# ══════════════════════════════════════════════════════════════════
# CACHE GC
# ══════════════════════════════════════════════════════════════════
def cache_gc():
    global PEAK_CONCURRENT
    while True:
        time.sleep(60)
        now = time.time()
        with SEARCH_CACHE_LOCK:
            dead = [k for k, v in SEARCH_CACHE.items()
                    if now - v.get("ts", 0) > SEARCH_CACHE_TTL]
            for k in dead:
                SEARCH_CACHE.pop(k, None)
        with _activity_lock:
            cutoff = now - LIVE_WINDOW
            for uid in list(ACTIVE_USERS.keys()):
                if ACTIVE_USERS[uid] < cutoff:
                    del ACTIVE_USERS[uid]
            if len(ACTIVE_USERS) > PEAK_CONCURRENT:
                PEAK_CONCURRENT = len(ACTIVE_USERS)
        with _member_lock:
            for uid, (_, ts) in list(_member_cache.items()):
                if now - ts > MEMBERSHIP_CACHE_TTL * 2:
                    _member_cache.pop(uid, None)
        with _pending_lock:
            for uid, (_, _, ts) in list(_pending_query.items()):
                if now - ts > PENDING_QUERY_TTL:
                    _pending_query.pop(uid, None)
        with _flood_lock:
            for uid, until in list(_muted_until.items()):
                if until < now - 300:
                    _muted_until.pop(uid, None)
        with _seen_updates_lock:
            cutoff = now - 600
            for k in [k for k, v in _seen_updates.items() if v < cutoff]:
                del _seen_updates[k]
        today = _today_utc()
        with _quota_lock:
            for uid, (day, _) in list(_user_daily.items()):
                if day != today:
                    _user_daily.pop(uid, None)