Spaces:
Running

File size: 35,998 Bytes
2905c16
 
 
 
 
 
 
 
 
1857916
2905c16
 
 
 
 
 
 
 
 
 
 
1857916
2905c16
1857916
2905c16
 
 
 
1857916
2905c16
 
6a14713
2905c16
 
 
 
 
 
 
 
 
 
 
 
6a14713
 
 
 
1857916
a02505a
1857916
a02505a
1857916
2905c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a14713
2905c16
 
 
 
 
 
b4b205e
2905c16
 
b4b205e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2905c16
b4b205e
 
 
 
 
 
 
 
2905c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a14713
2905c16
 
 
6a14713
 
 
 
 
 
 
 
 
 
 
 
2905c16
 
 
 
b4b205e
2905c16
 
 
 
 
 
 
 
 
 
6a14713
 
2905c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
"""Flask-приложение и все HTTP-маршруты /api/*, /health и /.

Вынесено из bot.py без изменения поведения (шаг «каркас», пункт 2.7 роадмапа). bot.py запускается как __main__,
поэтому здесь нет `import bot`; общее состояние лежит в runtime.py, сессии в session_auth.py, а отправка
сообщений в Telegram идёт через хук runtime.send_message (его регистрирует бот).
Маршруты, которым нужен сам бот (/api/bot_info, /webhook), остаются в bot.py и регистрируются на этом же app.
"""
import os
import threading as _threading
from datetime import datetime

import requests
from flask import Flask, request, jsonify
from flask_cors import CORS

import ai_router
from text_utils import set_markdown_mode
from providers.gemini_provider import UnsupportedFileError
from ai_clients import check_keys_status
from stats_report import get_stats_report
from database import (get_user, get_user_by_username, register_user,
                      set_ai_model, remove_subscription,
                      has_active_sub, get_balance, get_referral_count, get_all_users, get_stats,
                      is_maintenance, set_setting, get_setting, log_admin_grant,
                      get_mini_app_chats, save_mini_app_chat, delete_mini_app_chat,
                      log_session_activity, get_user_purchase_history, grant_pro,
                      check_daily_limit, check_feature_quota, increment_feature_usage,
                      IMAGE_GEN_FEATURE, IMAGE_GEN_DAILY_LIMIT, check_token_quota)
from runtime import (OWNER_ID, BOT_USERNAME, is_privileged,
                     GenerationInProgress, _generation_lock, resolve_model_id, is_pro_model,
                     _finalize_usage_async, get_mime_for_extension,
                     MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS_TOTAL_BYTES,
                     auth_tokens as _auth_tokens, send_message as _notify)
from session_auth import (_make_session_token, _require_authed_user_id,
                          _verify_telegram_webapp_init_data,
                          check_admin_auth as _check_admin_auth)

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}}, supports_credentials=False)

# Флаги функций и конфиг клиентов: /api/app-config, /api/admin/flags, /api/admin/app_version, /api/admin/maintenance (пункт 1.1)
from app_config import app_config_bp
app.register_blueprint(app_config_bp)

# Загрузка больших вложений частями: /api/upload/* (прокси Vercel режет тела > ~4.5 МБ)
from uploads import uploads_bp, read_upload, discard_upload, UploadError
app.register_blueprint(uploads_bp)

# Оплата подписки: ЮKassa (виджет) и CryptoBot (динамический инвойс): /api/pay/*, /api/admin/pay/*
from payments import payments_bp, start_reconciler
app.register_blueprint(payments_bp)
start_reconciler()   # фоновая сверка зависших оплат (PAY_RECONCILE_INTERVAL, 0 — выключить)

@app.before_request
def _set_client_format_mode():
    # Сайт, мини-апп и приложения (/api/*) рендерят markdown и блоки кода; Telegram-бот (/webhook)
    # отправляет обычный текст — ему остаётся plain-промпт. Ставим явно на каждый запрос.
    set_markdown_mode(request.path.startswith("/api/"))

@app.after_request
def after_request(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Admin-Secret")
    response.headers.add("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS")
    return response

# App version / auto-update переехал на сайт: приложение теперь берёт
# версию напрямую из https://elyon-ai-web.vercel.app/downloads/version.json
# (статический файл, обновляется через push_release.ps1 в Elyon-AI-Web-repo),
# без похода через бота вообще. См. update_service.dart.


@app.route("/api/chat", methods=["POST", "OPTIONS"])
def api_chat():
    if request.method == "OPTIONS":
        return "", 204
    try:
        authed_uid, err = _require_authed_user_id()
        if err: return err
        data     = request.json
        user_id  = authed_uid  # было: data.get("user_id") — клиентский user_id без проверки, позволял имперсонировать любого
        model    = data.get("model", "elyon_nova")
        messages = data.get("messages", [])
        if not messages:
            return jsonify({"error": "Missing messages"}), 400
        if is_maintenance() and not is_privileged(user_id):
            return jsonify({"error": "Maintenance in progress"}), 503

        model_id = resolve_model_id(model)
        if not model_id:
            return jsonify({"error": "Unknown model"}), 400
        model_is_pro = is_pro_model(model_id)
        user_is_pro  = has_active_sub(user_id)
        if model_is_pro and not user_is_pro:
            return jsonify({"error": "No active subscription"}), 403

        if not is_privileged(user_id):
            # БЫЛО: сюда передавался model_is_pro вместо user_is_pro — Pro-подписчик на бесплатной
            # модели (Nova) получал дневной лимит 15 вместо 30 — именно это было видно в "0/15" на сайте.
            allowed, current, limit = check_daily_limit(user_id, user_is_pro)
            if not allowed:
                return jsonify({"error": "daily_limit", "limit": limit}), 429
            token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro)
            if not token_allowed:
                return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429

        reply = usage = None
        try:
            with _generation_lock(user_id):
                reply, usage = ai_router.ask(model_id, messages)
        except GenerationInProgress:
            return jsonify({"error": "already_generating"}), 429
        # Счётчики в фоне ПОСЛЕ того, как готов ответ — 3-4 сетевых похода к Turso больше не задерживают ответ.
        _finalize_usage_async(user_id, usage, "miniapp")
        return jsonify({"reply": reply})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/user/<int:user_id>", methods=["GET", "OPTIONS"])
def api_user(user_id):
    if request.method == "OPTIONS": return "", 204
    authed_uid, err = _require_authed_user_id()
    if err: return err
    if authed_uid != user_id:
        return jsonify({"error": "Unauthorized"}), 403
    user = get_user(user_id)
    if not user: return jsonify({"error": "User not found"}), 404
    is_pro = has_active_sub(user_id)  # один раз, дальше передаётся в check_token_quota вместо её внутреннего повторного has_active_sub
    token_allowed, token_info = check_token_quota(user_id, is_pro=is_pro)
    # Карточка "Messages today" на сайте раньше всегда показывала статичное "0 / 15" и не учитывала Pro-лимит 30 —
    # ответ этого endpoint вообще не содержал этих полей.
    _, daily_current, daily_limit = check_daily_limit(user_id, is_pro)
    return jsonify({
        "user_id": user[0], "username": user[1], "role": user[3],
        "ai_model": user[4], "sub_type": user[5], "sub_until": user[6],
        "balance": get_balance(user_id), "referrals": get_referral_count(user_id),
        "has_sub": is_pro,
        "ref_link": f"https://t.me/{BOT_USERNAME}?start={user_id}",
        "purchase_history": [list(p) for p in get_user_purchase_history(user_id)],
        "token_usage": token_info["usage"], "token_limits": token_info["limits"],
        "daily_messages": daily_current, "daily_limit": daily_limit,
    })

@app.route("/api/chats/<int:user_id>", methods=["GET", "OPTIONS"])
def api_get_chats(user_id):
    if request.method == "OPTIONS": return "", 204
    authed_uid, err = _require_authed_user_id()
    if err: return err
    if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403
    return jsonify({"chats": get_mini_app_chats(user_id)})

@app.route("/api/chats/<int:user_id>", methods=["POST", "OPTIONS"])
def api_save_chat(user_id):
    if request.method == "OPTIONS": return "", 204
    authed_uid, err = _require_authed_user_id()
    if err: return err
    if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403
    try:
        data = request.json
        chat_id = data.get("chat_id")
        if not chat_id: return jsonify({"error": "Missing chat_id"}), 400
        save_mini_app_chat(user_id, chat_id, data.get("title","New chat"),
                           data.get("model","gpt"), data.get("messages",[]))
        return jsonify({"ok": True})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/chats/<int:user_id>/<chat_id>", methods=["DELETE", "OPTIONS"])
def api_delete_chat(user_id, chat_id):
    if request.method == "OPTIONS": return "", 204
    authed_uid, err = _require_authed_user_id()
    if err: return err
    if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403
    delete_mini_app_chat(user_id, chat_id)
    return jsonify({"ok": True})

# Лимиты вложений в одном сообщении (сайт/мини-апп/приложение): Free — 1 файл, Pro — до 4. Проверяется на сервере
# (клиенты тоже ограничивают UI по этим числам, но доверять им нельзя).
MAX_ATTACHMENTS_FREE = 1
MAX_ATTACHMENTS_PRO  = 4
# MAX_ATTACHMENT_BYTES (20 МБ на файл) и MAX_ATTACHMENTS_TOTAL_BYTES (30 МБ на сообщение) живут в runtime.py

_FILE_MIME_MAP = {
    ".py":"text/x-python",".js":"text/javascript",".cpp":"text/x-c++",".c":"text/x-c",".java":"text/x-java",
    ".txt":"text/plain",".md":"text/plain",".csv":"text/csv",".json":"application/json",".html":"text/html",
    ".css":"text/css",".sql":"text/plain",".gif":"image/gif",".png":"image/png",".jpg":"image/jpeg",
    ".jpeg":"image/jpeg",".webp":"image/webp",".pdf":"application/pdf",
    ".heic":"image/heic",".heif":"image/heif",   # Gemini принимает HEIC/HEIF как есть (фото с Samsung/iPhone)
}

_HEIF_BRANDS = {b"heic": "image/heic", b"heix": "image/heic", b"hevc": "image/heic", b"hevx": "image/heic",
                b"heim": "image/heic", b"heis": "image/heic", b"mif1": "image/heif", b"msf1": "image/heif"}


def _sniff_image_mime(blob: bytes):
    """Тип изображения по первым байтам (не по имени и не по тому, что сказал клиент). None, если это не картинка из списка."""
    if blob[:3] == b"\xff\xd8\xff":
        return "image/jpeg"
    if blob[:8] == b"\x89PNG\r\n\x1a\n":
        return "image/png"
    if blob[:6] in (b"GIF87a", b"GIF89a"):
        return "image/gif"
    if blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
        return "image/webp"
    if blob[4:8] == b"ftyp":
        return _HEIF_BRANDS.get(blob[8:12])
    return None


def _resolve_file_mime(file_name: str, file_type: str, blob: bytes = b"") -> str:
    """MIME вложения. Приоритет: то, что сказал клиент (кроме octet-stream), иначе расширение; если по первым байтам это
    известная картинка (JPEG/PNG/GIF/WebP/HEIC/HEIF), верим содержимому. Android-проводник часто не знает HEIC (octet-stream),
    сайт подставлял text/plain: файл принимали за текст и отклоняли («Формат файла не поддерживается»)."""
    if file_type and file_type != "application/octet-stream":
        mime = file_type
    else:
        ext = os.path.splitext((file_name or "").lower())[1]
        mime = _FILE_MIME_MAP.get(ext) or get_mime_for_extension(file_name or "") or "application/octet-stream"
    sniffed = _sniff_image_mime(blob) if blob else None
    if sniffed and mime != sniffed:
        return sniffed   # сигнатура картинки в начале файла надёжнее имени и догадки клиента (сайт раньше считал неизвестное text/plain)
    return mime


@app.route("/api/file_b64", methods=["POST", "OPTIONS"])
def api_file_b64():
    """JSON: {model, prompt, history, lang, files:[{name,type,data(base64)}]}. Старый формат одного файла
    (file_name/file_type/file_data) поддержан для необновлённых клиентов."""
    if request.method == "OPTIONS": return "", 204
    try:
        authed_uid, err = _require_authed_user_id()
        if err: return err
        import base64 as b64
        data      = request.json or {}
        user_id   = authed_uid
        model     = data.get("model", "elyon_nova")
        prompt    = data.get("prompt") or ""
        history   = data.get("history", [])
        lang      = "en" if str(data.get("lang", "ru")).lower().startswith("en") else "ru"
        raw_files = data.get("files")
        if not raw_files:
            raw_files = [{"name": data.get("file_name", "file"),
                          "type": data.get("file_type", "application/octet-stream"),
                          "data": data.get("file_data", "")}]
        if not isinstance(raw_files, list) or not raw_files:
            return jsonify({"error": "No files"}), 400
        if is_maintenance() and not is_privileged(user_id):
            return jsonify({"error": "Maintenance in progress"}), 503
        model_id = resolve_model_id(model)
        if not model_id:
            return jsonify({"error": "Unknown model"}), 400
        user_is_pro = has_active_sub(user_id)
        if is_pro_model(model_id) and not user_is_pro:
            return jsonify({"error": "No active subscription"}), 403
        is_privileged_user = is_privileged(user_id)
        attach_limit = MAX_ATTACHMENTS_PRO if (user_is_pro or is_privileged_user) else MAX_ATTACHMENTS_FREE
        if len(raw_files) > attach_limit:
            return jsonify({"error": f"Max {attach_limit} attachment(s) per message on your plan",
                            "code": "too_many_attachments", "limit": attach_limit}), 400
        if not is_privileged_user:
            # Раньше здесь проверялся только токен-лимит: сообщения с файлом увеличивали дневной
            # счётчик, но не упирались в дневной лимит — файлы можно было слать бесконечно.
            allowed, _cur, limit = check_daily_limit(user_id, user_is_pro)
            if not allowed:
                return jsonify({"error": "daily_limit", "limit": limit}), 429
            token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro)
            if not token_allowed:
                return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429
        files = []
        total = 0
        used_uploads = []
        for rf in raw_files:
            if not isinstance(rf, dict): return jsonify({"error": "Bad file entry"}), 400
            name = str(rf.get("name") or "file")
            if rf.get("upload_id"):
                # большой файл, загруженный частями (см. uploads.py): берём байты из временного хранилища
                try:
                    blob = read_upload(user_id, rf.get("upload_id"))
                except UploadError as ue:
                    return jsonify({"error": ue.message, "code": ue.code}), ue.status
                used_uploads.append(rf.get("upload_id"))
            else:
                try:
                    blob = b64.b64decode(rf.get("data") or "")
                except Exception:
                    return jsonify({"error": f"Bad file data: {name}"}), 400
            if not blob: return jsonify({"error": f"Empty file: {name}"}), 400
            if len(blob) > MAX_ATTACHMENT_BYTES:
                return jsonify({"error": f"File too large (max 20 MB): {name}"}), 413
            total += len(blob)
            files.append((blob, _resolve_file_mime(name, str(rf.get("type") or ""), blob), name))
        if total > MAX_ATTACHMENTS_TOTAL_BYTES:
            return jsonify({"error": "Attachments too large (max 30 MB total)"}), 413
        reply = usage = None
        try:
            with _generation_lock(user_id):
                reply, usage = ai_router.ask_with_files(model_id, files, prompt, history, lang)
        except GenerationInProgress:
            return jsonify({"error": "already_generating"}), 429
        except UnsupportedFileError as e:
            return jsonify({"error": str(e), "code": "unsupported_file"}), 400
        for _uid in used_uploads:          # ответ получен: временные файлы больше не нужны (при ошибке остаются до TTL для повтора)
            discard_upload(user_id, _uid)
        _finalize_usage_async(user_id, usage, "miniapp")
        return jsonify({"reply": reply})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/voice", methods=["POST", "OPTIONS"])
def api_voice():
    """Голос → текст (сайт/миниапп/десктоп). multipart/form-data:
    file (аудио), user_id. Не отправляет в AI самостоятельно — только возвращает
    транскрипт, клиент показывает его в поле ввода для подтверждения/редактирования
    перед отправкой — как и обычное текстовое сообщение."""
    if request.method == "OPTIONS": return "", 204
    try:
        authed_uid, err = _require_authed_user_id()
        if err: return err
        user_id = authed_uid
        if is_maintenance() and not is_privileged(user_id):
            return jsonify({"error": "Maintenance in progress"}), 503
        if "file" not in request.files: return jsonify({"error": "No audio file"}), 400
        f = request.files["file"]
        audio_bytes = f.read()
        filename = f.filename or "voice.webm"
        transcript = ai_router.transcribe_voice(audio_bytes, filename)
        if not transcript or not transcript.strip():
            return jsonify({"error": "Не удалось распознать речь"}), 422
        return jsonify({"transcript": transcript})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/generate_image", methods=["POST", "OPTIONS"])
def api_generate_image():
    """Генерация картинок (сайт/миниапп/десктоп), только Pro. JSON:
    {user_id, prompt}. Квота 3/сутки (сброс 00:00 UTC), та же таблица feature_usage,
    что и у бота (общий лимит на юзера независимо от клиента). Возвращает
    {image: base64, mime_type}, как в data URI на клиенте."""
    if request.method == "OPTIONS": return "", 204
    try:
        authed_uid, err = _require_authed_user_id()
        if err: return err
        import base64 as b64
        data    = request.json or {}
        user_id = authed_uid
        prompt  = (data.get("prompt") or "").strip()
        if not prompt: return jsonify({"error": "Missing prompt"}), 400
        if is_maintenance() and not is_privileged(user_id):
            return jsonify({"error": "Maintenance in progress"}), 503
        if not has_active_sub(user_id) and not is_privileged(user_id):
            return jsonify({"error": "No active subscription"}), 403
        allowed, current, limit = check_feature_quota(user_id, IMAGE_GEN_FEATURE, IMAGE_GEN_DAILY_LIMIT)
        if not allowed and not is_privileged(user_id):
            return jsonify({"error": "daily_limit", "limit": limit}), 429
        image_bytes = mime_type = None
        try:
            with _generation_lock(user_id):
                image_bytes, mime_type = ai_router.generate_image(prompt)
        except GenerationInProgress:
            return jsonify({"error": "already_generating"}), 429
        # Счётчики в фоне — картинка уже готова, ждать Turso пользователю не надо.
        _threading.Thread(target=lambda: (
            increment_feature_usage(user_id, IMAGE_GEN_FEATURE),
            log_session_activity(user_id, "miniapp"),
        ), daemon=True).start()
        return jsonify({"image": b64.b64encode(image_bytes).decode(), "mime_type": mime_type})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/file", methods=["POST", "OPTIONS"])
def api_file():
    if request.method == "OPTIONS": return "", 204
    try:
        authed_uid, err = _require_authed_user_id()
        if err: return err
        import json as json_lib
        user_id     = authed_uid
        model       = request.form.get("model", "elyon_nova")
        prompt      = request.form.get("prompt", "Проанализируй этот файл")
        history     = json_lib.loads(request.form.get("history","[]"))
        if "file" not in request.files: return jsonify({"error": "No file"}), 400
        model_id = resolve_model_id(model)
        if not model_id:
            return jsonify({"error": "Unknown model"}), 400
        user_is_pro = has_active_sub(user_id)
        if is_pro_model(model_id) and not user_is_pro:
            return jsonify({"error": "No active subscription"}), 403
        if not is_privileged(user_id):
            token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro)
            if not token_allowed:
                return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429
        f          = request.files["file"]
        file_bytes = f.read(); file_name = f.filename or "file"
        mime_type  = f.content_type or "application/octet-stream"
        if mime_type == "application/octet-stream":
            ext = os.path.splitext(file_name.lower())[1]
            mime_map = {".py":"text/x-python",".js":"text/javascript",".txt":"text/plain",
                        ".md":"text/plain",".csv":"text/csv",".json":"application/json"}
            mime_type = mime_map.get(ext, "application/octet-stream")
        reply, usage = ai_router.ask_with_file(model_id, file_bytes, mime_type, file_name, prompt, history)
        _finalize_usage_async(user_id, usage, "miniapp")
        return jsonify({"reply": reply})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ── Auth ──────────────────────────────────────────────────────────────────


GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID",
    "468899724697-mct44qubsrdaps8ll6m4npv34k6jeucn.apps.googleusercontent.com")

def _upsert_web_user(email, first_name, last_name, avatar="", provider="email"):
    # Используем публичные функции database.py, а не сырой SQL через
    # database.cursor/database.conn — после миграции на Turso (libsql_client)
    # этих атрибутов больше не существует (там теперь внутренний _exec()),
    # из-за чего Google/email авторизация падала с AttributeError: "module 'database'
    # has no attribute 'cursor'".
    existing = get_user_by_username(email)
    if existing:
        user_id = existing[0]
    else:
        user_id = abs(hash(email + provider)) % (10**12)
        register_user(user_id, email)
    return {"user_id":user_id,"email":email,"first_name":first_name,
            "last_name":last_name,"avatar":avatar,"provider":provider}

@app.route("/api/auth/google_profile", methods=["POST","OPTIONS"])
def auth_google_profile():
    if request.method == "OPTIONS": return "", 204
    try:
        data = request.json or {}
        # РАНЬШЕ клиент присылал готовый объект profile, взятый им самим из Google — сервер никак
        # не проверял, что этот JSON действительно пришёл от Google, а не придуман атакующим напрямую в
        # POST /api/auth/google_profile — можно было заявиться любым email. Теперь клиент шлёт сам access_token,
        # а сервер сам запрашивает им профиль у Google — только так он доказан, что токен действительно выдал Google.
        access_token = data.get("access_token", "")
        if not access_token:
            return jsonify({"ok":False,"error":"Missing access_token"}), 400
        try:
            g = requests.get("https://www.googleapis.com/oauth2/v3/userinfo",
                              headers={"Authorization": f"Bearer {access_token}"}, timeout=10)
        except requests.RequestException as e:
            return jsonify({"ok":False,"error":f"Google verification failed: {e}"}), 502
        if g.status_code != 200:
            return jsonify({"ok":False,"error":"Invalid or expired Google token"}), 401
        profile = g.json()
        email = profile.get("email","")
        if not email: return jsonify({"ok":False,"error":"No email"}), 400
        user = _upsert_web_user(email, profile.get("given_name",""),
                                profile.get("family_name",""), profile.get("picture",""), "google")
        return jsonify({"ok":True,"user":user,"token":_make_session_token(user["user_id"])})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/auth/telegram_webapp", methods=["POST","OPTIONS"])
def auth_telegram_webapp():
    """Авторизация для Мини-Аппа внутри Telegram: клиент шлёт сырой подписанный
    Telegram.WebApp.initData целиком (не initDataUnsafe.user отдельно), сервер сам проверяет HMAC-подпись."""
    if request.method == "OPTIONS": return "", 204
    try:
        init_data = (request.json or {}).get("init_data", "")
        tg_user = _verify_telegram_webapp_init_data(init_data)
        if not tg_user or not tg_user.get("id"):
            return jsonify({"ok":False,"error":"Invalid Telegram initData"}), 401
        user_id  = int(tg_user["id"])
        username = tg_user.get("username", "")
        register_user(user_id, username)
        user = get_user(user_id)
        sub_type = user[5] if user else "none"
        web_user = {
            "user_id": user_id,
            "email": f"{username}@telegram" if username else f"tg_{user_id}@telegram",
            "first_name": tg_user.get("first_name",""), "last_name": tg_user.get("last_name",""),
            "avatar": "", "provider": "telegram", "username": username, "sub_type": sub_type,
        }
        return jsonify({"ok":True,"user":web_user,"token":_make_session_token(user_id)})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/auth/email", methods=["POST","OPTIONS"])
def auth_email():
    if request.method == "OPTIONS": return "", 204
    try:
        import hashlib as _hl
        data     = request.json or {}
        action   = data.get("action","signin")
        email    = data.get("email","").lower().strip()
        password = data.get("password","")
        if not email or not password:
            return jsonify({"ok":False,"error":"Missing email or password"}), 400
        pw_hash = _hl.sha256(password.encode()).hexdigest()
        if action == "signup":
            if get_user_by_username(email):
                return jsonify({"ok":False,"error":"Email already registered"}), 409
            user_id = abs(hash(email + pw_hash)) % (10**12)
            register_user(user_id, email)
            set_setting(f"pw_{email}", pw_hash)
            user = _upsert_web_user(email, data.get("first_name",""), data.get("last_name",""), "", "email")
            return jsonify({"ok":True,"verify":False,"user":user,"token":_make_session_token(user["user_id"])})
        else:
            stored = get_setting(f"pw_{email}")
            if not stored or stored != pw_hash:
                return jsonify({"ok":False,"error":"Invalid email or password"}), 401
            user = _upsert_web_user(email, "", "", "", "email")
            return jsonify({"ok":True,"user":user,"token":_make_session_token(user["user_id"])})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/auth/telegram_token", methods=["POST","OPTIONS"])
def auth_telegram_token():
    if request.method == "OPTIONS": return "", 204
    try:
        data  = request.json or {}
        token = data.get("token","")
        if not token: return jsonify({"ok":False,"error":"Missing token"}), 400
        info = _auth_tokens.get(token)
        if not info: return jsonify({"ok":False,"error":"Invalid token"}), 401
        if datetime.now().timestamp() > info["expires"]:
            _auth_tokens.pop(token, None)
            return jsonify({"ok":False,"error":"Token expired"}), 401
        _auth_tokens.pop(token, None)
        user_id  = info["user_id"]; username = info["username"]
        register_user(user_id, username)
        user     = get_user(user_id)
        sub_type = user[5] if user else "none"
        web_user = {
            "user_id": user_id,
            "email":   f"{username}@telegram" if username else f"tg_{user_id}@telegram",
            "first_name": info["first_name"], "last_name": "",
            "avatar": "", "provider": "telegram",
            "username": username, "sub_type": sub_type,
        }
        return jsonify({"ok":True,"user":web_user,"token":_make_session_token(user_id)})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/admin/stats", methods=["GET","OPTIONS"])
def api_admin_stats():
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    return jsonify(get_stats())

@app.route("/api/admin/stats_report", methods=["GET","OPTIONS"])
def api_admin_stats_report():
    """Данные для двух баннеров админ-панели: «Сегодня (UTC)» с почасовым графиком и «За всё время» с дневным."""
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    try:
        return jsonify(get_stats_report())
    except Exception as e:
        print(f"[stats_report] {e}", flush=True)
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/admin/users", methods=["GET","OPTIONS"])
def api_admin_users():
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    users = get_all_users()
    return jsonify({"users": [{"user_id":u[0],"username":u[1] or "","role":u[3] or "default user",
        "sub_type":u[5] or "none","balance":u[7] if len(u)>7 else 0} for u in users]})


# ══════════════════════════════════════════════════════════════════
# Admin API — /give sub и /remove sub из веб-панели (задача 2 и 4)
# ══════════════════════════════════════════════════════════════════

# _check_admin_auth() живёт в session_auth.py (check_admin_auth): её используют и маршруты из app_config.py

@app.route("/api/admin/give_sub", methods=["POST","OPTIONS"])
def api_admin_give_sub():
    """
    Выдать Elyon Pro из веб-панели.
    Headers: X-Admin-Secret
    Body: {"target":"@username","days":30,"forever":false}
    """
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    try:
        data    = request.json or {}
        target  = data.get("target","").strip().lstrip("@")
        days    = int(data.get("days", 30))
        forever = bool(data.get("forever", False))
        user = get_user_by_username(target)
        if not user:
            return jsonify({"ok":False,"error":f"User @{target} not found"}), 404
        user_id   = user[0]
        until_str = grant_pro(user_id, days=None if forever else days, forever=forever)
        set_ai_model(user_id, "elyon_sol")
        log_admin_grant(user_id, "subscription", "pro", until_str, OWNER_ID)
        try:
            _notify(user_id, f"✅ Подписка Elyon Pro активирована (до {until_str}).")
        except:
            pass
        return jsonify({"ok":True,"user_id":user_id,"tier":"pro","until":until_str})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/admin/remove_sub", methods=["POST","OPTIONS"])
def api_admin_remove_sub():
    """
    Снять подписку из веб-панели.
    Headers: X-Admin-Id: OWNER_ID
    Body: {"target":"@username"}
    """
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    try:
        target = (request.json or {}).get("target","").strip().lstrip("@")
        user = get_user_by_username(target)
        if not user:
            return jsonify({"ok":False,"error":f"User @{target} not found"}), 404
        user_id = user[0]
        remove_subscription(user_id)
        try:
            _notify(user_id, "ℹ️ Твоя подписка деактивирована администратором.")
        except:
            pass
        return jsonify({"ok":True,"user_id":user_id})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/api/admin/test_keys", methods=["GET","OPTIONS"])
def api_admin_test_keys():
    """Проверить API ключи из веб-панели."""
    if request.method == "OPTIONS": return "", 204
    if not _check_admin_auth():
        return jsonify({"ok":False,"error":"Unauthorized"}), 403
    try:
        status = check_keys_status()
        return jsonify({"ok":True,"keys":status})
    except Exception as e:
        return jsonify({"ok":False,"error":str(e)}), 500

@app.route("/", methods=["GET"])
def index():
    # HF Space открывает "/" по умолчанию и показывал 404 — сюда заходят люди, а не только пингер.
    return jsonify({"status": "ok", "service": "Elyon AI backend", "docs": "https://elyon-ai-web.vercel.app/app.html"})

@app.route("/health", methods=["GET"])
def health():
    return jsonify({"status": "ok"})