File size: 45,852 Bytes
6f80d8b
 
 
2a32f00
6f80d8b
 
 
 
 
e6e4cd6
 
6f80d8b
bc18334
e6e4cd6
bc18334
8b919e0
bc18334
 
6f80d8b
 
 
8b919e0
bc18334
 
 
 
 
a390f1a
6f80d8b
bc18334
8b919e0
bc18334
6f80d8b
 
bc18334
6f80d8b
 
bc18334
 
6f80d8b
ce448b5
bc18334
6f80d8b
 
 
 
 
 
 
bc18334
 
6f80d8b
bc18334
6f80d8b
 
bc18334
6f80d8b
bc18334
 
 
6f80d8b
bc18334
 
 
 
6f80d8b
8b919e0
e6e4cd6
bc18334
 
6f80d8b
 
bc18334
6f80d8b
e6e4cd6
 
bc18334
e6e4cd6
 
 
500c24f
e6e4cd6
bc18334
 
e6e4cd6
bc18334
6f80d8b
e6e4cd6
bc18334
6f80d8b
e6e4cd6
bc18334
 
 
 
 
 
 
6f80d8b
 
bc18334
 
6f80d8b
bc18334
 
 
 
e6e4cd6
bc18334
 
 
 
 
 
 
6f80d8b
 
bc18334
6f80d8b
e6e4cd6
bc18334
6f80d8b
e6e4cd6
bc18334
6f80d8b
bc18334
 
 
 
e6e4cd6
6f80d8b
bc18334
 
 
 
 
e6e4cd6
6f80d8b
 
 
 
 
 
 
 
bc18334
6f80d8b
 
 
 
bc18334
6f80d8b
 
 
 
 
 
 
 
 
bc18334
 
 
 
6f80d8b
 
bc18334
6f80d8b
 
 
 
 
 
 
 
 
 
 
 
bc18334
 
6f80d8b
bc18334
 
 
6f80d8b
 
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
 
 
bc18334
 
 
 
 
 
 
 
6f80d8b
bc18334
6f80d8b
bc18334
 
 
 
6f80d8b
bc18334
 
 
 
 
6f80d8b
 
bc18334
6f80d8b
 
 
bc18334
6f80d8b
 
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
 
bc18334
 
6f80d8b
 
 
bc18334
 
6f80d8b
bc18334
 
 
6f80d8b
 
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
bc18334
 
 
 
 
6f80d8b
bc18334
 
 
6f80d8b
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
bc18334
 
6f80d8b
 
bc18334
6f80d8b
 
bc18334
 
 
 
6f80d8b
bc18334
6f80d8b
 
bc18334
6f80d8b
bc18334
 
6f80d8b
 
bc18334
 
6f80d8b
bc18334
 
 
 
 
 
6f80d8b
bc18334
6f80d8b
 
 
 
 
 
 
 
 
bc18334
 
 
 
 
6f80d8b
bc18334
6f80d8b
 
 
 
bc18334
6f80d8b
bc18334
 
6f80d8b
 
 
bc18334
 
6f80d8b
bc18334
6f80d8b
 
 
bc18334
 
 
6f80d8b
 
 
bc18334
6f80d8b
 
 
 
 
 
bc18334
 
 
 
 
6f80d8b
bc18334
6f80d8b
bc18334
6f80d8b
bc18334
 
 
 
 
6f80d8b
 
bc18334
6f80d8b
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
 
 
 
 
 
98a25c5
6f80d8b
 
 
 
bc18334
98a25c5
bc18334
 
 
38eda2f
bc18334
6f80d8b
bc18334
6f80d8b
bc18334
 
6f80d8b
 
 
 
bc18334
6f80d8b
bc18334
6f80d8b
 
 
 
 
 
bc18334
bd4b9f2
bc18334
 
 
 
6f80d8b
 
bc18334
6f80d8b
 
 
bc18334
 
6f80d8b
 
bc18334
 
6f80d8b
 
bc18334
6f80d8b
daa7bba
c4bb4cb
6f80d8b
daa7bba
6f80d8b
 
 
bc18334
0318b2a
bc18334
 
 
 
6f80d8b
 
bc18334
6f80d8b
 
 
bc18334
6f80d8b
 
 
bc18334
 
6f80d8b
 
bc18334
 
6f80d8b
 
 
bc18334
 
6f80d8b
 
 
 
bc18334
 
 
 
 
 
a4eb49c
6f80d8b
a4eb49c
6f80d8b
bc18334
6f80d8b
 
 
 
 
bc18334
6f80d8b
 
bc18334
6f80d8b
 
 
bc18334
 
 
 
6f80d8b
 
 
bc18334
6f80d8b
 
 
bc18334
 
 
 
 
 
 
 
 
 
 
6f80d8b
 
 
 
bc18334
 
6f80d8b
 
 
 
 
bc18334
 
6f80d8b
bc18334
6f80d8b
 
 
 
 
 
 
 
 
 
 
 
 
bc18334
6f80d8b
 
 
 
 
 
bc18334
6f80d8b
 
 
bc18334
 
6f80d8b
 
bc18334
6f80d8b
 
bc18334
6f80d8b
 
 
 
bc18334
 
6f80d8b
 
 
bc18334
6f80d8b
 
 
 
 
 
 
 
bc18334
6f80d8b
 
 
 
 
 
bc18334
 
 
6f80d8b
 
 
 
 
 
 
bc18334
 
6f80d8b
 
bc18334
6f80d8b
 
 
bc18334
6f80d8b
bc18334
6f80d8b
 
bc18334
6f80d8b
bc18334
 
6f80d8b
bc18334
6f80d8b
 
 
 
 
 
 
 
 
 
 
 
bc18334
 
 
 
6f80d8b
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
 
 
 
bc18334
 
6f80d8b
bc18334
 
 
6f80d8b
bc18334
 
6f80d8b
bc18334
daa7bba
 
6f80d8b
 
 
 
bc18334
6f80d8b
 
bc18334
6f80d8b
bc18334
6f80d8b
 
 
bc18334
 
98a25c5
bc18334
397b649
0318b2a
da6d436
6f80d8b
bc18334
6f80d8b
daa7bba
6f80d8b
 
 
38eda2f
bc18334
6f80d8b
51849f1
6f80d8b
 
 
 
 
 
bc18334
6f80d8b
 
 
 
bc18334
6f80d8b
 
bc18334
6f80d8b
bc18334
 
6f80d8b
bc18334
 
6f80d8b
bc18334
 
6f80d8b
 
 
bc18334
6f80d8b
bc18334
6f80d8b
bc18334
6f80d8b
 
 
 
 
 
 
bc18334
6f80d8b
bc18334
 
 
 
6f80d8b
 
 
bc18334
6f80d8b
 
 
bc18334
6f80d8b
 
 
 
 
bc18334
 
 
 
6f80d8b
c4bb4cb
 
bc18334
 
 
 
 
 
 
6f80d8b
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
6f80d8b
bc18334
 
 
6f80d8b
 
 
c4bb4cb
 
bc18334
 
 
 
 
 
 
 
 
 
6f80d8b
bc18334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for
import hmac
import hashlib
import json
from urllib.parse import unquote, parse_qs, quote
import time
from datetime import datetime
import logging
import threading
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError

# --- Configuration ---
BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Use environment variable or default
HOST = '0.0.0.0'
PORT = 7860
DATA_FILE = 'data.json' # File to store visited user data

# Hugging Face Hub Configuration
REPO_ID = "flpolprojects/teledata"
HF_TOKEN = os.getenv("HF_TOKEN") # Write token
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", HF_TOKEN) # Read token (defaults to write token if not set)
BACKUP_INTERVAL = 900 # Seconds (15 minutes)

app = Flask(__name__)
app.secret_key = os.urandom(24) # Needed for flash messages or sessions if used later

# Logging Setup
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# --- Hugging Face Hub Functions ---

def download_db_from_hf():
    if not HF_TOKEN_READ:
        logging.warning("HF_TOKEN_READ not set. Skipping download from Hugging Face Hub.")
        return False
    try:
        logging.info(f"Attempting to download {DATA_FILE} from {REPO_ID}...")
        hf_hub_download(
            repo_id=REPO_ID,
            filename=DATA_FILE,
            repo_type="dataset",
            token=HF_TOKEN_READ,
            local_dir=".",
            local_dir_use_symlinks=False,
            force_download=True, # Ensure we get the latest version
            resume_download=False
        )
        logging.info(f"{DATA_FILE} successfully downloaded from Hugging Face Hub.")
        return True
    except RepositoryNotFoundError:
        logging.warning(f"Repository {REPO_ID} not found on Hugging Face Hub. Will use/create local file.")
        return False
    except HfHubHTTPError as e:
        if e.response.status_code == 404:
             logging.warning(f"{DATA_FILE} not found in repository {REPO_ID}. Will use/create local file.")
        else:
             logging.error(f"HTTP error downloading {DATA_FILE} from Hugging Face Hub: {e}")
        return False
    except Exception as e:
        logging.error(f"Error downloading {DATA_FILE} from Hugging Face Hub: {e}")
        return False

def upload_db_to_hf():
    if not HF_TOKEN:
        logging.warning("HF_TOKEN not set. Skipping upload to Hugging Face Hub.")
        return False
    if not os.path.exists(DATA_FILE):
        logging.warning(f"{DATA_FILE} not found locally. Skipping upload.")
        return False
    try:
        api = HfApi()
        logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}...")
        api.upload_file(
            path_or_fileobj=DATA_FILE,
            path_in_repo=DATA_FILE,
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            commit_message=f"Automated user data backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        logging.info(f"{DATA_FILE} successfully uploaded to Hugging Face Hub.")
        return True
    except Exception as e:
        logging.error(f"Error uploading {DATA_FILE} to Hugging Face Hub: {e}")
        return False

def periodic_backup():
    logging.info(f"Starting periodic backup thread. Interval: {BACKUP_INTERVAL} seconds.")
    while True:
        time.sleep(BACKUP_INTERVAL)
        logging.info("Initiating scheduled backup...")
        upload_db_to_hf()

# --- Data Handling ---

def load_users():
    # Attempt download first
    download_db_from_hf()

    if not os.path.exists(DATA_FILE):
        logging.warning(f"{DATA_FILE} not found. Initializing empty user data.")
        return {}
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            users_data = json.load(f)
            if not isinstance(users_data, dict):
                logging.warning(f"{DATA_FILE} does not contain a valid JSON dictionary. Resetting.")
                return {}
            logging.info(f"Loaded {len(users_data)} user records from {DATA_FILE}.")
            return users_data
    except json.JSONDecodeError:
        logging.error(f"Error decoding JSON from {DATA_FILE}. Returning empty data.")
        # Consider backing up the corrupted file here
        return {}
    except Exception as e:
        logging.error(f"Error loading user data from {DATA_FILE}: {e}")
        return {}

def save_users(users_data):
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(users_data, f, ensure_ascii=False, indent=4)
        logging.info(f"Saved {len(users_data)} user records to {DATA_FILE}.")
        # Attempt upload after saving locally
        upload_db_to_hf()
    except Exception as e:
        logging.error(f"Error saving user data to {DATA_FILE}: {e}")


# Load initial data on startup
visited_users = load_users()

# --- Telegram Verification ---

def verify_telegram_data(init_data_str):
    try:
        parsed_data = parse_qs(init_data_str)
        received_hash = parsed_data.pop('hash', [None])[0]

        if not received_hash:
            logging.warning("Verification failed: No hash found in initData.")
            return None, False

        data_check_list = []
        for key, value in sorted(parsed_data.items()):
            # Ensure values are strings before appending
            data_check_list.append(f"{key}={value[0]}")
        data_check_string = "\n".join(data_check_list)

        secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
        calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()

        if calculated_hash == received_hash:
            auth_date = int(parsed_data.get('auth_date', [0])[0])
            current_time = int(time.time())
            # Allow slightly older data, adjust timeout as needed (e.g., 3600 for 1 hour)
            if current_time - auth_date > 86400: # 24 hours tolerance
                 logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).")
            # logging.info("Telegram data verified successfully.")
            return parsed_data, True
        else:
            logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}")
            return parsed_data, False
    except Exception as e:
        logging.error(f"Error verifying Telegram data: {e}")
        return None, False

# --- Templates ---

TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
    <title>Morshen Group - IT Holding</title>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --tg-theme-bg-color: var(--tg-bg-color, #181a1b);
            --tg-theme-text-color: var(--tg-text-color, #ffffff);
            --tg-theme-hint-color: var(--tg-hint-color, #aaaaaa);
            --tg-theme-link-color: var(--tg-link-color, #8774e1);
            --tg-theme-button-color: var(--tg-button-color, #8774e1);
            --tg-theme-button-text-color: var(--tg-button-text-color, #ffffff);
            --tg-theme-secondary-bg-color: var(--tg-secondary-bg-color, #222425);

            --bg-color: var(--tg-theme-bg-color);
            --card-bg: var(--tg-theme-secondary-bg-color);
            --text-color: var(--tg-theme-text-color);
            --text-secondary-color: var(--tg-theme-hint-color);
            --accent-color: var(--tg-theme-button-color);
            --accent-text-color: var(--tg-theme-button-text-color);
            --link-color: var(--tg-theme-link-color);
            --green-accent: #34c759;
            --red-accent: #ff3b30;

            --border-radius-s: 8px;
            --border-radius-m: 12px;
            --border-radius-l: 16px;
            --padding-s: 10px;
            --padding-m: 20px;
            --padding-l: 30px;
            --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;

            --shadow-color: rgba(0, 0, 0, 0.2);
            --card-shadow: 0 4px 15px var(--shadow-color);
            --button-shadow: 0 3px 8px var(--shadow-color);
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        html {
            background-color: var(--bg-color);
            color: var(--text-color);
            font-family: var(--font-family);
            scroll-behavior: smooth;
        }

        body {
            background: linear-gradient(180deg, color-mix(in srgb, var(--bg-color) 80%, black) 0%, var(--bg-color) 100%);
            color: var(--text-color);
            padding: var(--padding-m);
            padding-bottom: 120px; /* Space for fixed button */
            overscroll-behavior-y: none;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            line-height: 1.6;
            visibility: hidden; /* Hide until ready */
        }

        .container {
            max-width: 650px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: var(--padding-l);
        }

        /* Header & Logo */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--padding-s);
        }
        .logo { display: flex; align-items: center; gap: var(--padding-s); }
        .logo img, .logo-icon {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background-color: var(--card-bg);
            object-fit: cover;
            border: 2px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 2px 5px var(--shadow-color);
        }
        .logo span { font-size: 1.6em; font-weight: 700; }

        /* Buttons */
        .btn {
            display: inline-flex; align-items: center; justify-content: center;
            padding: 12px var(--padding-m); border-radius: var(--border-radius-m);
            background: var(--accent-color); color: var(--accent-text-color);
            text-decoration: none; font-weight: 600; border: none; cursor: pointer;
            transition: all 0.25s ease-out; gap: 8px; font-size: 1em;
            box-shadow: var(--button-shadow);
        }
        .btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 5px 12px var(--shadow-color);
        }
        .btn-secondary {
            background: var(--card-bg);
            color: var(--accent-color);
            border: 1px solid color-mix(in srgb, var(--accent-color) 50%, transparent);
        }
        .btn-secondary:hover {
            background: color-mix(in srgb, var(--card-bg) 90%, white);
        }
        .btn-green {
            background: var(--green-accent); color: white;
        }
         .btn-green:hover {
             background: color-mix(in srgb, var(--green-accent) 90%, black);
         }

        /* Tags */
        .tag-container { margin: var(--padding-m) 0; display: flex; flex-wrap: wrap; gap: 8px; }
        .tag {
            display: inline-flex; align-items: center; gap: 5px;
            background: color-mix(in srgb, var(--card-bg) 70%, var(--accent-color) 10%);
            color: var(--text-secondary-color);
            padding: 6px 12px; border-radius: var(--border-radius-s); font-size: 0.85em; font-weight: 500;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .tag i { opacity: 0.8; }

        /* Cards */
        .section-card {
            background-color: var(--card-bg);
            border-radius: var(--border-radius-l);
            padding: var(--padding-m);
            margin-bottom: 0; /* Removed default bottom margin */
            box-shadow: var(--card-shadow);
            border: 1px solid rgba(255, 255, 255, 0.05);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .section-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px var(--shadow-color);
        }

        /* Typography */
        .section-title { font-size: 2em; font-weight: 800; margin-bottom: var(--padding-s); line-height: 1.2; }
        .section-subtitle { font-size: 1.2em; font-weight: 500; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }
        .description { font-size: 1em; line-height: 1.7; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }

        /* Stats Grid */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: var(--padding-s); margin-top: var(--padding-m); text-align: center; }
        .stat-item { background-color: rgba(255, 255, 255, 0.05); padding: var(--padding-s) var(--padding-m); border-radius: var(--border-radius-m); }
        .stat-value { font-size: 1.7em; font-weight: 700; display: block; }
        .stat-label { font-size: 0.8em; color: var(--text-secondary-color); display: block; text-transform: uppercase; letter-spacing: 0.5px; }

        /* List Items */
        .list-container { display: flex; flex-direction: column; gap: var(--padding-s); margin-top: var(--padding-s); }
        .list-item { background-color: color-mix(in srgb, var(--card-bg) 80%, black); padding: var(--padding-m); border-radius: var(--border-radius-m); display: flex; align-items: center; gap: var(--padding-m); font-size: 1.1em; font-weight: 500; }
        .list-item i { font-size: 1.4em; color: var(--accent-color); opacity: 0.9; width: 25px; text-align: center; }

        /* Footer */
        .footer-greeting { text-align: center; color: var(--text-secondary-color); font-size: 0.9em; margin-top: var(--padding-l); }

        /* Fixed Button */
        .save-card-button {
            position: fixed;
            bottom: 25px;
            left: 50%;
            transform: translateX(-50%);
            padding: 14px 28px;
            border-radius: 30px;
            background: var(--green-accent);
            color: white;
            text-decoration: none;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            z-index: 1000;
            box-shadow: 0 6px 20px rgba(52, 199, 89, 0.4);
            font-size: 1.1em;
            display: flex;
            align-items: center;
            gap: 10px;
            white-space: nowrap;
        }
        .save-card-button:hover {
            opacity: 0.9;
            transform: translateX(-50%) scale(1.05);
            box-shadow: 0 8px 25px rgba(52, 199, 89, 0.5);
        }
        .save-card-button i { font-size: 1.2em; }

        /* Modal Styles */
        .modal {
            display: none; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1001; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            overflow: auto; /* Enable scroll if needed */
            background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            padding-top: 10vh; /* Location of the box */
            animation: fadeIn 0.3s ease-out;
        }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        .modal-content {
            background-color: var(--card-bg, #2c2c2e);
            color: var(--text-color, #ffffff);
            margin: 5% auto; /* 5% from the top and centered */
            padding: var(--padding-l, 30px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            width: 90%; /* Could be more or less, depending on screen size */
            max-width: 480px;
            border-radius: var(--border-radius-l, 16px);
            text-align: center;
            position: relative;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
            animation: slideIn 0.4s ease-out;
        }
         @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .modal-close {
            color: var(--text-secondary-color, #aaa);
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
            transition: color 0.2s ease;
        }
        .modal-close:hover,
        .modal-close:focus {
            color: var(--text-color, #fff);
            text-decoration: none;
        }
        .modal-title {
            font-size: 1.5em;
            font-weight: 700;
            margin-bottom: var(--padding-s);
        }
        .modal-text {
            font-size: 1.2em;
            line-height: 1.6;
            margin-bottom: var(--padding-s);
            word-wrap: break-word;
            font-weight: 500;
        }
        .modal-text strong {
            font-weight: 700;
            color: var(--accent-color);
        }
        .modal-instruction {
             font-size: 1em;
             color: var(--text-secondary-color, #a0a0a5);
             margin-top: var(--padding-m);
             font-style: italic;
        }

        /* Icons */
        .icon { display: inline-block; font-style: normal; margin-right: 8px; }
        .icon-save::before { content: '💾'; }
        .icon-web::before { content: '🌐'; }
        .icon-mobile::before { content: '📱'; }
        .icon-code::before { content: '💻'; }
        .icon-ai::before { content: '🧠'; }
        .icon-quantum::before { content: '⚛️'; }
        .icon-business::before { content: '💼'; }
        .icon-speed::before { content: '⚡️'; }
        .icon-complexity::before { content: '🧩'; }
        .icon-experience::before { content: '⏳'; }
        .icon-clients::before { content: '👥'; }
        .icon-market::before { content: '📈'; }
        .icon-location::before { content: '📍'; }
        .icon-global::before { content: '🌍'; }
        .icon-innovation::before { content: '💡'; }
        .icon-contact::before { content: '💬'; }
        .icon-link::before { content: '🔗'; }
        .icon-leader::before { content: '🏆'; }
        .icon-company::before { content: '🏢'; }

        /* Responsive */
        @media (max-width: 600px) {
            body { padding: var(--padding-s); padding-bottom: 100px; }
            .container { gap: var(--padding-m); }
            .section-title { font-size: 1.8em; }
            .section-subtitle { font-size: 1.1em; }
            .btn { padding: 10px var(--padding-m); font-size: 0.95em; }
            .save-card-button { padding: 12px 24px; font-size: 1em; bottom: 20px; }
            .modal-content { width: 95%; padding: var(--padding-m); }
            .modal-title { font-size: 1.3em; }
            .modal-text { font-size: 1.1em; }
            .modal-instruction { font-size: 0.9em; }
        }
    </style>
</head>
<body>
    <div class="container">

        <section class="morshen-group-intro">
            <div class="header">
                 <div class="logo">
                     <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
                    <span>Morshen Group</span>
                </div>
                <a href="#" class="btn btn-secondary contact-link"><i class="icon icon-contact"></i>Связаться</a>
            </div>
            <div class="tag-container">
                <span class="tag"><i class="icon icon-leader"></i>Лидер инноваций 2025</span>
                 <span class="tag"><i class="icon icon-global"></i>Международный Холдинг</span>
            </div>
            <h1 class="section-title">Создаем будущее IT сегодня</h1>
            <p class="description">
                Мы — международный IT холдинг, объединяющий передовые технологические компании для создания прорывных решений мирового уровня в сферах AI, квантовых вычислений и разработки ПО.
            </p>
             <a href="#" class="btn btn-green contact-link" style="width: 100%; margin-top: var(--padding-s);">
                 <i class="icon icon-contact"></i>Обсудить ваш проект
             </a>
        </section>

         <section class="ecosystem-header">
             <h2 class="section-title">Экосистема <span style="color: var(--accent-color);">Инноваций</span></h2>
             <p class="description">
                 В состав холдинга входят специализированные компании, каждая из которых является экспертом в своей области передовых технологий.
             </p>
         </section>

        <section class="section-card">
            <div class="logo">
                 <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo">
                <span style="font-size: 1.5em; font-weight: 600;">Morshen Alpha</span>
            </div>
            <div class="tag-container">
                <span class="tag"><i class="icon icon-ai"></i>Искусственный интеллект</span>
                <span class="tag"><i class="icon icon-quantum"></i>Квантовые технологии</span>
                <span class="tag"><i class="icon icon-business"></i>Стратегические решения</span>
            </div>
            <p class="description">
                Флагман холдинга. Занимаемся R&D в области AI и квантовых технологий, разрабатываем передовые бизнес-решения, формирующие будущее индустрии.
            </p>
            <div class="stats-grid">
                <div class="stat-item">
                    <span class="stat-value"><i class="icon icon-global"></i> 3+</span>
                    <span class="stat-label">Страны</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><i class="icon icon-clients"></i> 3K+</span>
                    <span class="stat-label">Клиенты</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><i class="icon icon-market"></i> 5+</span>
                    <span class="stat-label">Лет на рынке</span>
                </div>
            </div>
        </section>

        <section class="section-card">
             <div class="logo">
                 <img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 50px; height: 50px;">
                <span style="font-size: 1.5em; font-weight: 600;">Holmgard Studio</span>
            </div>
             <div class="tag-container">
                 <span class="tag"><i class="icon icon-web"></i>Веб-разработка</span>
                 <span class="tag"><i class="icon icon-mobile"></i>Мобильные приложения</span>
                 <span class="tag"><i class="icon icon-code"></i>Энтерпрайз ПО</span>
             </div>
             <p class="description">
                Студия разработки полного цикла. Создаем высокотехнологичные веб-сайты, мобильные приложения и кастомное ПО для бизнеса любого масштаба, используя современные стеки и методологии.
             </p>
             <div class="stats-grid">
                 <div class="stat-item">
                     <span class="stat-value"><i class="icon icon-experience"></i> 10+</span>
                     <span class="stat-label">Лет опыта</span>
                 </div>
                 <div class="stat-item">
                     <span class="stat-value"><i class="icon icon-complexity"></i> Highload</span>
                     <span class="stat-label">Сложные проекты</span>
                 </div>
                 <div class="stat-item">
                     <span class="stat-value"><i class="icon icon-speed"></i> Agile</span>
                     <span class="stat-label">Быстрый запуск</span>
                 </div>
             </div>
             <div style="display: flex; gap: var(--padding-s); margin-top: var(--padding-m); flex-wrap: wrap;">
                 <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon icon-link"></i>На сайт</a>
                 <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon icon-contact"></i>Связаться</a>
             </div>
        </section>

        <section>
            <h2 class="section-title"><i class="icon icon-global"></i> Глобальное Присутствие</h2>
            <p class="description">Наши решения и команды работают в ключевых регионах Центральной Азии:</p>
            <div class="list-container">
                <div class="list-item"><i class="icon icon-location"></i>Узбекистан</div>
                <div class="list-item"><i class="icon icon-location"></i>Казахстан</div>
                <div class="list-item"><i class="icon icon-location"></i>Кыргызстан</div>
            </div>
        </section>

        <footer class="footer-greeting">
             <p id="greeting">Загрузка данных...</p>
        </footer>

    </div>

    <button class="save-card-button" id="save-card-btn">
        <i class="icon icon-save"></i>Сохранить визитку
    </button>

    <!-- The Modal -->
    <div id="saveModal" class="modal">
      <div class="modal-content">
        <span class="modal-close" id="modal-close-btn">×</span>
        <h3 class="modal-title">Контактная информация</h3>
        <p class="modal-text"><strong>+996 500 398 754</strong></p>
        <p class="modal-text">Morshen Group, IT Holding</p>
        <p class="modal-instruction">Сделайте скриншот, чтобы сохранить контакт.</p>
      </div>
    </div>


    <script>
        const tg = window.Telegram.WebApp;

        function applyTheme(themeParams) {
            document.documentElement.style.setProperty('--tg-bg-color', themeParams.bg_color || '#181a1b');
            document.documentElement.style.setProperty('--tg-text-color', themeParams.text_color || '#ffffff');
            document.documentElement.style.setProperty('--tg-hint-color', themeParams.hint_color || '#aaaaaa');
            document.documentElement.style.setProperty('--tg-link-color', themeParams.link_color || '#8774e1');
            document.documentElement.style.setProperty('--tg-button-color', themeParams.button_color || '#8774e1');
            document.documentElement.style.setProperty('--tg-button-text-color', themeParams.button_text_color || '#ffffff');
            document.documentElement.style.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color || '#222425');
            console.log("Theme applied:", themeParams);
        }

        function setupTelegram() {
            if (!tg || !tg.initData) {
                 console.error("Telegram WebApp script not loaded or initData is missing.");
                 const greetingElement = document.getElementById('greeting');
                 if(greetingElement) greetingElement.textContent = 'Ошибка загрузки Telegram.';
                 document.body.style.visibility = 'visible'; // Show body anyway
                 return;
             }

            tg.ready();
            tg.expand();
            applyTheme(tg.themeParams);
            tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); // Listen for theme changes

             // Send initData for verification and user logging
             fetch('/verify', {
                 method: 'POST',
                 headers: {
                     'Content-Type': 'application/json',
                 },
                 body: JSON.stringify({ initData: tg.initData }),
             })
             .then(response => response.json())
             .then(data => {
                 if (data.status === 'ok' && data.verified) {
                     console.log('Backend verification successful.');
                 } else {
                     console.warn('Backend verification failed:', data.message);
                     // Optionally show a non-intrusive warning
                 }
             })
             .catch(error => {
                 console.error('Error sending initData for verification:', error);
             });

             // User Greeting (using unsafe data for immediate feedback)
             const user = tg.initDataUnsafe?.user;
             const greetingElement = document.getElementById('greeting');
             if (user) {
                 const name = user.first_name || user.username || 'Гость';
                 greetingElement.textContent = `Приветствуем, ${name}! 👋`;
             } else {
                 greetingElement.textContent = 'Добро пожаловать!';
                 console.warn('Telegram User data (initDataUnsafe.user) not available.');
             }

             // Contact Links
             const contactButtons = document.querySelectorAll('.contact-link');
             contactButtons.forEach(button => {
                 button.addEventListener('click', (e) => {
                     e.preventDefault();
                     tg.openTelegramLink('https://t.me/morshenkhan'); // Replace with actual contact username
                     if (tg.HapticFeedback) tg.HapticFeedback.impactOccurred('light');
                 });
             });

             // Modal Setup
             const modal = document.getElementById("saveModal");
             const saveCardBtn = document.getElementById("save-card-btn");
             const closeBtn = document.getElementById("modal-close-btn");

             if (saveCardBtn && modal && closeBtn) {
                 saveCardBtn.addEventListener('click', (e) => {
                     e.preventDefault();
                     modal.style.display = "block";
                     if (tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
                 });

                 closeBtn.addEventListener('click', () => {
                     modal.style.display = "none";
                 });

                 // Close modal if clicked outside the content
                 modal.addEventListener('click', (event) => { // Listen on modal overlay itself
                     if (event.target === modal) {
                         modal.style.display = "none";
                     }
                 });
             } else {
                 console.error("Modal elements not found!");
             }

             document.body.style.visibility = 'visible'; // Make body visible now
             console.log("Telegram Mini App setup complete.");
         }

        // Initialize Telegram WebApp
        if (window.Telegram && window.Telegram.WebApp) {
            setupTelegram();
        } else {
            console.warn("Telegram WebApp script not immediately available. Waiting for load event.");
            window.addEventListener('load', setupTelegram);
             // Further fallback timeout
             setTimeout(() => {
                 if (document.body.style.visibility !== 'visible') {
                      console.error("Telegram WebApp script loading fallback timeout triggered.");
                      const greetingElement = document.getElementById('greeting');
                      if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса.';
                      document.body.style.visibility = 'visible'; // Force display anyway
                  }
             }, 4000); // Increased timeout
        }
    </script>
</body>
</html>
"""

ADMIN_TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Посетители</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --admin-bg-color: #1f2937; /* Dark Gray */
            --admin-card-bg: #374151; /* Medium Gray */
            --admin-text-color: #f3f4f6; /* Light Gray */
            --admin-text-secondary-color: #9ca3af; /* Gray */
            --admin-accent-color: #60a5fa; /* Blue */
            --admin-border-color: #4b5563; /* Darker Gray */
            --admin-shadow-color: rgba(0, 0, 0, 0.3);
            --border-radius: 12px;
            --padding: 20px;
        }
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--admin-bg-color);
            color: var(--admin-text-color);
            margin: 0;
            padding: var(--padding);
            line-height: 1.6;
        }
        .container { max-width: 1200px; margin: 0 auto; }
        h1 { text-align: center; color: var(--admin-accent-color); font-weight: 700; margin-bottom: 30px; }
        .controls { display: flex; justify-content: center; gap: 15px; margin-bottom: 30px; flex-wrap: wrap;}
        .control-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            background-color: var(--admin-accent-color);
            color: #fff;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 5px var(--admin-shadow-color);
        }
        .control-btn:hover {
            background-color: #3b82f6; /* Darker Blue */
            transform: translateY(-1px);
            box-shadow: 0 4px 10px var(--admin-shadow-color);
        }
        .control-btn.download { background-color: #34d399; } /* Green */
        .control-btn.download:hover { background-color: #059669; }
        .user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: var(--padding); }
        .user-card {
            background-color: var(--admin-card-bg);
            border-radius: var(--border-radius);
            padding: var(--padding);
            box-shadow: 0 4px 15px var(--admin-shadow-color);
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            border: 1px solid var(--admin-border-color);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .user-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 25px var(--admin-shadow-color);
        }
        .user-card img {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            margin-bottom: 15px;
            object-fit: cover;
            border: 3px solid var(--admin-border-color);
            background-color: var(--admin-bg-color); /* Placeholder bg */
        }
        .user-card .name { font-weight: 700; font-size: 1.2em; margin-bottom: 5px; color: var(--admin-text-color); }
        .user-card .username { color: var(--admin-accent-color); margin-bottom: 10px; font-size: 0.95em; font-weight: 500; }
        .user-card .details { font-size: 0.9em; color: var(--admin-text-secondary-color); word-break: break-all; line-height: 1.5; }
        .user-card .timestamp { font-size: 0.8em; color: var(--admin-text-secondary-color); margin-top: 15px; font-style: italic; }
        .no-users { text-align: center; color: var(--admin-text-secondary-color); margin-top: 40px; font-size: 1.1em; }
        .alert {
            background-color: #f87171; /* Red */
            color: #fff;
            border-left: 6px solid #dc2626; /* Darker Red */
            margin-bottom: 25px;
            padding: 15px 20px;
            border-radius: 8px;
            text-align: center;
            font-weight: 600;
            box-shadow: 0 2px 5px var(--admin-shadow-color);
        }
        a { color: var(--admin-accent-color); text-decoration: none; }
        a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Панель Администратора - Посетители</h1>
        <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div>

        <div class="controls">
            <form method="POST" action="{{ url_for('backup_route') }}" style="display: inline;">
                <button type="submit" class="control-btn">Создать Резервную Копию</button>
            </form>
            <form method="GET" action="{{ url_for('download_route') }}" style="display: inline;">
                <button type="submit" class="control-btn download">Скачать Базу Данных</button>
            </form>
             <button class="control-btn" onclick="window.location.reload();">Обновить Список</button>
        </div>

        {% if users %}
            <div class="user-grid">
                {% for user in users|sort(attribute='visited_at', reverse=true) %}
                    <div class="user-card">
                        <img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%234b5563%27/%3e%3ctext x=%2750%25%27 y=%2750%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%239ca3af%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar" loading="lazy">
                        <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
                        {% if user.username %}
                            <div class="username"><a href="https://t.me/{{ user.username }}" target="_blank">@{{ user.username }}</a></div>
                        {% else %}
                             <div class="username">Нет username</div>
                        {% endif %}
                        <div class="details">
                            ID: {{ user.id }} <br>
                            Язык: {{ user.language_code or 'N/A' }} <br>
                            Телефон: <span style="color: var(--admin-text-secondary-color); font-style: italic;">Недоступен</span>
                        </div>
                         <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
                    </div>
                {% endfor %}
            </div>
        {% else %}
            <p class="no-users">Пока нет данных о посетителях.</p>
        {% endif %}
    </div>
</body>
</html>
"""


# --- Flask Routes ---

@app.route('/')
def index():
    return render_template_string(TEMPLATE)

@app.route('/verify', methods=['POST'])
def verify_data():
    global visited_users
    try:
        data = request.get_json()
        init_data_str = data.get('initData')
        if not init_data_str:
            logging.warning("Verification request missing initData.")
            return jsonify({"status": "error", "message": "Missing initData"}), 400

        user_data_parsed, is_valid = verify_telegram_data(init_data_str)

        user_info_dict = {}
        if user_data_parsed and 'user' in user_data_parsed:
            try:
                # Decode JSON string within the 'user' field
                user_json_str = unquote(user_data_parsed['user'][0])
                user_info_dict = json.loads(user_json_str)
            except (KeyError, IndexError, json.JSONDecodeError, TypeError) as e:
                logging.error(f"Could not parse user JSON from initData: {e} - Data: {user_data_parsed.get('user')}")
                user_info_dict = {} # Ensure it's a dict even on error

        if is_valid:
            user_id = user_info_dict.get('id')
            if user_id:
                user_id_str = str(user_id) # Use string keys for JSON consistency
                now = time.time()
                update_data = {
                     'id': user_id,
                     'first_name': user_info_dict.get('first_name'),
                     'last_name': user_info_dict.get('last_name'),
                     'username': user_info_dict.get('username'),
                     'photo_url': user_info_dict.get('photo_url'),
                     'language_code': user_info_dict.get('language_code'),
                     'visited_at': now,
                     'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S UTC') # Explicit UTC
                 }
                # Update the global dictionary and save
                visited_users[user_id_str] = update_data
                save_users(visited_users) # Save after modification
                logging.info(f"User visit recorded/updated for ID: {user_id_str}")

            return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
        else:
            logging.warning(f"Verification failed for user ID: {user_info_dict.get('id', 'Unknown')}")
            return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403

    except Exception as e:
        logging.exception("Critical error in /verify endpoint") # Log full traceback
        return jsonify({"status": "error", "message": "Internal server error"}), 500

@app.route('/admin')
def admin_panel():
    # WARNING: This route is unprotected! Add proper authentication/authorization for production.
    # Load fresh data for admin view, though 'visited_users' global should be up-to-date
    current_users = load_users()
    users_list = list(current_users.values())
    logging.info(f"Admin panel accessed. Displaying {len(users_list)} users.")
    return render_template_string(ADMIN_TEMPLATE, users=users_list)

@app.route('/backup', methods=['POST'])
def backup_route():
    # Manual backup trigger
    # WARNING: Unprotected route
    logging.info("Manual backup requested via /backup route.")
    if upload_db_to_hf():
        # Optionally add a success message (e.g., using flash)
        pass
    else:
        # Optionally add an error message
        pass
    return redirect(url_for('admin_panel')) # Redirect back to admin

@app.route('/download', methods=['GET'])
def download_route():
    # Manual download trigger
    # WARNING: Unprotected route
    global visited_users
    logging.info("Manual download requested via /download route.")
    if download_db_from_hf():
        visited_users = load_users() # Reload data after download
        # Optionally add a success message
    else:
        # Optionally add an error message
        pass
    return redirect(url_for('admin_panel')) # Redirect back to admin


# --- Main Execution ---

if __name__ == '__main__':
    # Initial check for HF tokens
    if not HF_TOKEN:
        logging.warning("!!! HF_TOKEN environment variable is not set. Uploads to Hugging Face Hub will be disabled.")
    if not HF_TOKEN_READ:
        logging.warning("!!! HF_TOKEN_READ environment variable is not set. Downloads from Hugging Face Hub will be disabled (falling back to local file).")

    # Start the periodic backup thread
    if HF_TOKEN: # Only start if upload is possible
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
    else:
        logging.warning("Periodic backup thread not started because HF_TOKEN is not set.")


    logging.warning("--- SECURITY WARNING ---")
    logging.warning("The /admin, /backup, /download routes are NOT protected by authentication.")
    logging.warning("Anyone knowing the URL can access visitor data and trigger actions.")
    logging.warning("Implement proper security (e.g., password protection, IP restriction) before deploying.")
    logging.warning("------------------------")
    logging.info(f"Starting Flask server on http://{HOST}:{PORT}")
    logging.info(f"Ensure this address is accessible and configured in BotFather for your Mini App.")
    logging.info(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
    logging.info(f"User data file: {DATA_FILE}")
    logging.info(f"Hugging Face Repo: {REPO_ID}")

    # Use Waitress or Gunicorn for production instead of app.run()
    # from waitress import serve
    # serve(app, host=HOST, port=PORT)
    app.run(host=HOST, port=PORT, debug=False) # debug=False for production