File size: 25,315 Bytes
b497eb4
 
 
 
 
 
 
34014b0
 
9222a6a
 
34014b0
 
86c086e
9222a6a
b497eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9222a6a
 
 
b497eb4
 
 
 
 
 
 
86c086e
34014b0
 
 
 
 
 
 
 
 
9222a6a
34014b0
 
9222a6a
 
 
34014b0
9222a6a
 
34014b0
86c086e
9222a6a
34014b0
9222a6a
86c086e
34014b0
 
 
 
b497eb4
 
34014b0
 
b497eb4
86c086e
 
 
 
b497eb4
34014b0
86c086e
34014b0
 
 
b497eb4
86c086e
34014b0
 
 
 
86c086e
b497eb4
 
 
86c086e
b497eb4
 
 
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
 
 
86c086e
b497eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9222a6a
b497eb4
9222a6a
b497eb4
 
 
 
 
 
8641578
 
 
b497eb4
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
 
 
 
 
 
 
86c086e
b497eb4
 
 
 
 
86c086e
b497eb4
86c086e
 
 
 
 
 
b497eb4
 
 
 
 
86c086e
b497eb4
 
 
 
 
 
 
 
 
 
 
 
86c086e
b497eb4
 
 
 
86c086e
b497eb4
 
 
 
86c086e
b497eb4
 
 
 
 
 
 
 
 
 
 
86c086e
b497eb4
 
 
 
 
be3c306
86c086e
b497eb4
 
 
 
8641578
b497eb4
9222a6a
b497eb4
9222a6a
b497eb4
 
 
 
9222a6a
be3c306
 
9222a6a
 
 
 
 
 
be3c306
 
 
 
 
86c086e
be3c306
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
 
8641578
b497eb4
 
9222a6a
b497eb4
8641578
b497eb4
 
 
86c086e
 
 
b497eb4
86c086e
b497eb4
 
 
 
 
 
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
 
8641578
9222a6a
b497eb4
 
 
 
 
 
 
 
 
 
 
9222a6a
 
 
b497eb4
 
86c086e
9222a6a
b497eb4
 
 
 
86c086e
9222a6a
b497eb4
9222a6a
b497eb4
 
 
 
 
 
 
 
 
 
 
9222a6a
 
b497eb4
 
86c086e
b497eb4
 
 
 
 
86c086e
9222a6a
b497eb4
9222a6a
b497eb4
 
86c086e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
 
 
 
 
 
 
 
 
 
86c086e
 
b497eb4
9222a6a
 
b497eb4
 
 
 
8641578
 
 
 
 
 
b497eb4
9222a6a
 
b497eb4
9222a6a
 
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
8641578
b497eb4
8641578
 
 
 
b497eb4
8641578
 
 
 
b497eb4
8641578
 
 
 
 
 
 
 
 
b497eb4
8641578
b497eb4
8641578
 
 
b497eb4
8641578
 
 
 
 
 
 
b497eb4
8641578
b497eb4
8641578
 
9222a6a
 
b497eb4
 
 
 
8641578
b497eb4
 
 
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
8641578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b497eb4
8641578
 
 
 
 
 
 
b497eb4
8641578
b497eb4
8641578
86c086e
 
b497eb4
 
8641578
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
import os
import re
import uuid
import pytz
import psycopg2
import requests
import gradio as gr
import json
import pickle
import base64

from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

from email.mime.text import MIMEText
from datetime import datetime, date
from dotenv import load_dotenv


# ================= LOAD ENV =================

load_dotenv()

DB_URL = os.getenv("DB_URL")
GMAIL_USER = os.getenv("GMAIL_USER")
CRON_SECRET = os.getenv("CRON")
HF_URL = os.getenv("HF_URL")

LEETCODE_API = "https://leetcode-api-vercel.vercel.app"

SCOPES = ["https://www.googleapis.com/auth/gmail.send"]
TOKEN_FILE = "token.pkl"


# ================= DB =================

def get_db():
    return psycopg2.connect(DB_URL, sslmode="require")


# ================= GMAIL =================

def get_gmail_service():

    creds = None

    if os.path.exists(TOKEN_FILE):
        try:
            with open(TOKEN_FILE, "rb") as f:
                creds = pickle.load(f)
        except:
            creds = None

    if creds and creds.expired and creds.refresh_token:
        try:
            creds.refresh(Request())

            with open(TOKEN_FILE, "wb") as f:
                pickle.dump(creds, f)

        except:
            creds = None

    if not creds:
        raise Exception("❌ token.pkl missing. Upload valid token.")

    return build("gmail", "v1", credentials=creds)


def send_email(to, subject, html):

    try:
        service = get_gmail_service()

        msg = MIMEText(html, "html")
        msg["To"] = to
        msg["From"] = GMAIL_USER
        msg["Subject"] = subject

        raw = base64.urlsafe_b64encode(
            msg.as_bytes()
        ).decode()

        body = {"raw": raw}

        service.users().messages().send(
            userId="me",
            body=body
        ).execute()

        print("βœ… Sent:", to)
        return True

    except Exception as e:
        print("❌ Gmail error:", e)
        return False


def create_email_template(title, content, unsubscribe_link, email_type="reminder", problem_link=None, difficulty=None):
    """Create a beautiful HTML email template"""
    
    # Color scheme based on email type
    colors = {
        "morning": {"primary": "#4CAF50", "secondary": "#81C784", "bg": "#E8F5E8"},
        "afternoon": {"primary": "#FF9800", "secondary": "#FFB74D", "bg": "#FFF3E0"},
        "night": {"primary": "#F44336", "secondary": "#EF5350", "bg": "#FFEBEE"},
        "verification": {"primary": "#2196F3", "secondary": "#64B5F6", "bg": "#E3F2FD"}
    }
    
    color = colors.get(email_type, colors["morning"])
    
    # Difficulty badge colors
    difficulty_colors = {
        "Easy": "#00B04F",
        "Medium": "#FFA116", 
        "Hard": "#FF375F"
    }
    
    # Handle special cases for verification emails
    if email_type == "verification":
        problem_button = f"""
        <div style="text-align: center; margin: 30px 0;">
            <a href="{unsubscribe_link}" 
               style="display: inline-block; background: linear-gradient(135deg, {color['primary']}, {color['secondary']}); 
                      color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px; 
                      font-weight: bold; font-size: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); 
                      transition: transform 0.2s;">
                βœ… Verify Email
            </a>
        </div>
        """
        tips_section = ""
        motivation_section = ""
        difficulty_badge = ""
    else:
        # Use provided problem_link or construct from title
        if problem_link:
            link_url = problem_link
        else:
            link_url = f"https://leetcode.com/problems/{title.lower().replace(' ', '-').replace('.', '')}"
            
        # Add difficulty badge
        if difficulty:
            diff_color = difficulty_colors.get(difficulty, "#666")
            difficulty_badge = f"""
            <div style="text-align: center; margin: 10px 0;">
                <span style="background-color: {diff_color}; color: white; padding: 4px 12px; 
                           border-radius: 12px; font-size: 12px; font-weight: bold;">
                    {difficulty}
                </span>
            </div>
            """
        else:
            difficulty_badge = ""
            
        problem_button = f"""
        <div style="text-align: center; margin: 30px 0;">
            <a href="{link_url}" 
               style="display: inline-block; background: linear-gradient(135deg, {color['primary']}, {color['secondary']}); 
                      color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px; 
                      font-weight: bold; font-size: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); 
                      transition: transform 0.2s;">
                πŸš€ Solve Problem
            </a>
        </div>
        """
        
        # Dynamic tips based on difficulty
        if difficulty == "Easy":
            tips_content = """
                <li>Focus on understanding the problem clearly</li>
                <li>Think about the simplest approach first</li>
                <li>Test with the given examples</li>
                <li>Consider edge cases like empty inputs</li>
            """
        elif difficulty == "Medium":
            tips_content = """
                <li>Break the problem into smaller subproblems</li>
                <li>Consider multiple approaches (greedy, DP, etc.)</li>
                <li>Think about time and space complexity</li>
                <li>Use appropriate data structures</li>
            """
        else:  # Hard
            tips_content = """
                <li>Study similar problems and patterns</li>
                <li>Don't rush - take time to understand</li>
                <li>Consider advanced algorithms and techniques</li>
                <li>Break it down step by step</li>
            """
            
        tips_section = f"""
        <!-- Tips Section -->
        <div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 25px 0;">
            <h3 style="color: #333; margin: 0 0 15px 0; font-size: 18px;">πŸ’‘ {difficulty} Problem Tips</h3>
            <ul style="color: #666; margin: 0; padding-left: 20px; line-height: 1.6;">
                {tips_content}
            </ul>
        </div>
        """
        
        motivation_quotes = [
            "The expert in anything was once a beginner.",
            "Every problem is a step forward in your journey.",
            "Consistency beats perfection every time.",
            "Code today, conquer tomorrow.",
            "Small progress is still progress."
        ]
        import random
        quote = random.choice(motivation_quotes)
        
        motivation_section = f"""
        <!-- Stats or Motivation -->
        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; margin: 25px 0;">
            <p style="color: white; margin: 0; font-size: 16px; font-style: italic;">
                "{quote}" πŸ’ͺ
            </p>
        </div>
        """
    
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>LeetCode Daily Tracker</title>
    </head>
    <body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5;">
        <div style="max-width: 600px; margin: 0 auto; background-color: white; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
            
            <!-- Header -->
            <div style="background: linear-gradient(135deg, {color['primary']}, {color['secondary']}); padding: 30px; text-align: center;">
                <h1 style="color: white; margin: 0; font-size: 28px; font-weight: 300;">
                    🧠 LeetCode Daily Tracker
                </h1>
                <p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0; font-size: 16px;">
                    Your coding journey companion
                </p>
            </div>
            
            <!-- Content -->
            <div style="padding: 40px 30px;">
                <div style="background-color: {color['bg']}; border-left: 4px solid {color['primary']}; padding: 20px; margin-bottom: 25px; border-radius: 0 8px 8px 0;">
                    {content}
                    {difficulty_badge}
                </div>
                
                {problem_button}
                
                {tips_section}
                
                {motivation_section}
            </div>
            
            <!-- Footer -->
            <div style="background-color: #f8f9fa; padding: 25px 30px; border-top: 1px solid #eee;">
                <div style="text-align: center;">
                    <p style="color: #666; margin: 0 0 15px 0; font-size: 14px;">
                        Keep coding, keep growing! 🌱
                    </p>
                    <div style="margin: 15px 0;">
                        <a href="https://leetcode.com" style="color: {color['primary']}; text-decoration: none; margin: 0 10px;">πŸ“Š LeetCode</a>
                        <span style="color: #ccc;">|</span>
                        <a href="https://github.com" style="color: {color['primary']}; text-decoration: none; margin: 0 10px;">πŸ’» GitHub</a>
                        <span style="color: #ccc;">|</span>
                        <a href="{unsubscribe_link if email_type != 'verification' else '#'}" style="color: #999; text-decoration: none; margin: 0 10px; font-size: 12px;">{'Unsubscribe' if email_type != 'verification' else ''}</a>
                    </div>
                    <p style="color: #999; font-size: 12px; margin: 15px 0 0 0;">
                        © 2024 LeetCode Daily Tracker. Made with ❀️ for coders.
                    </p>
                </div>
            </div>
        </div>
    </body>
    </html>
    """


# ================= VALIDATION =================

EMAIL_REGEX = re.compile(
    r"^[\w\.-]+@[\w\.-]+\.\w+$"
)


def valid_email(email):
    return bool(email and EMAIL_REGEX.match(email))


def valid_leetcode(username):

    if not username or len(username) < 3:
        return False

    try:
        r = requests.get(
            f"{LEETCODE_API}/{username}",
            timeout=8
        )
        return r.status_code == 200

    except:
        return False


# ================= LEETCODE =================

def get_daily_problem():
    try:
        r = requests.get(f"{LEETCODE_API}/daily", timeout=10)
        r.raise_for_status()

        d = r.json()
        print("πŸ“‘ Daily API response keys:", list(d.keys()))

        # Handle the current API format
        if "questionTitle" in d and "titleSlug" in d:
            title = d["questionTitle"]
            slug = d["titleSlug"]
            link = d.get("questionLink", f"https://leetcode.com/problems/{slug}/")
            difficulty = d.get("difficulty", "Unknown")
            print(f"βœ… Found daily problem: {title} ({difficulty}) - {slug}")
            return title, slug, link, difficulty

        # Fallback for older format
        if "title" in d and "titleSlug" in d:
            title = d["title"] 
            slug = d["titleSlug"]
            link = f"https://leetcode.com/problems/{slug}/"
            difficulty = d.get("difficulty", "Unknown")
            print(f"βœ… Found daily problem (fallback): {title} ({difficulty}) - {slug}")
            return title, slug, link, difficulty

        # If we can't find the expected fields, print the response
        print("❌ Available fields in API response:", list(d.keys()))
        raise Exception("Could not find title and slug in daily API response")

    except requests.exceptions.RequestException as e:
        print(f"❌ Network error calling daily API: {e}")
        raise Exception(f"Failed to fetch daily problem: {e}")
    
    except json.JSONDecodeError as e:
        print(f"❌ JSON decode error: {e}")
        raise Exception("Invalid JSON response from daily API")


def solved_today(username, slug):

    try:
        r = requests.get(
            f"{LEETCODE_API}/{username}/acSubmission?limit=20",
            timeout=10
        )

        if r.status_code != 200:
            return False

        d = r.json()

        if "submission" in d:
            subs = d["submission"]
        elif "data" in d:
            subs = d["data"]
        elif isinstance(d, list):
            subs = d
        else:
            return False

        today = date.today()

        for s in subs:

            if not isinstance(s, dict):
                continue

            if s.get("titleSlug") != slug:
                continue

            ts = s.get("timestamp")

            if not ts:
                continue

            solved = datetime.fromtimestamp(
                int(ts),
                tz=pytz.utc
            ).date()

            if solved == today:
                return True

        return False

    except:
        return False


# ================= SUBSCRIBE =================

def subscribe(username, email, timezone):

    if not valid_leetcode(username):
        return "❌ Invalid LeetCode username"

    if not valid_email(email):
        return "❌ Invalid email"

    conn = get_db()
    cur = conn.cursor()

    cur.execute("""
        SELECT email_verified, verification_token, unsubscribed
        FROM users WHERE email=%s
    """, (email,))

    row = cur.fetchone()

    # Existing user logic...
    if row:
        verified, token, unsub = row

        if verified and not unsub:
            cur.close()
            conn.close()
            return "⚠️ Already subscribed"

        if verified and unsub:
            cur.execute("""
                UPDATE users
                SET unsubscribed=false,
                    leetcode_username=%s,
                    timezone=%s,
                    last_sent_date=NULL,
                    last_sent_slot=NULL
                WHERE email=%s
            """, (username, timezone, email))

            conn.commit()
            cur.close()
            conn.close()
            return "βœ… Re-subscribed"

        # Resend verification with enhanced template
        verification_content = f"""
        <h2 style="color: #2196F3; margin: 0 0 15px 0;">Welcome back! πŸ‘‹</h2>
        <p style="color: #333; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
            We're excited to have you on your coding journey again! 
        </p>
        <p style="color: #666; font-size: 14px; margin: 0;">
            Click the verification button above to activate your daily LeetCode reminders.
        </p>
        """
        
        html_email = create_email_template(
            "Email Verification", 
            verification_content, 
            f"{HF_URL}?verify={token}", 
            "verification"
        )

        send_email(email, "πŸ”” Please verify your email", html_email)
        cur.close()
        conn.close()
        return "πŸ“© Verification re-sent"

    # New user - remove duplicate code
    token = uuid.uuid4().hex

    cur.execute("""
        INSERT INTO users(
            leetcode_username,email,timezone,
            email_verified,verification_token,unsubscribed
        )
        VALUES(%s,%s,%s,false,%s,false)
    """, (username, email, timezone, token))

    conn.commit()
    cur.close()
    conn.close()

    # Welcome email with enhanced template
    welcome_content = f"""
    <h2 style="color: #4CAF50; margin: 0 0 15px 0;">Welcome to the club! πŸŽ‰</h2>
    <p style="color: #333; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
        You're about to embark on an amazing coding journey with daily LeetCode challenges!
    </p>
    <div style="background-color: white; border: 2px dashed #4CAF50; padding: 15px; border-radius: 8px; margin: 15px 0;">
        <p style="color: #4CAF50; font-weight: bold; margin: 0 0 5px 0;">πŸ“… Your Schedule:</p>
        <p style="color: #666; font-size: 14px; margin: 0;">
            πŸŒ… <strong>9 AM</strong> - Daily problem<br>
            πŸŒ† <strong>3 PM</strong> - Gentle reminder<br>
            πŸŒ™ <strong>8 PM</strong> - Final reminder
        </p>
    </div>
    <p style="color: #666; font-size: 14px; margin: 0;">
        Click the verification button above to start receiving your personalized reminders!
    </p>
    """
    
    html_email = create_email_template(
        "Welcome", 
        welcome_content, 
        f"{HF_URL}?verify={token}", 
        "verification"
    )

    send_email(email, "🎯 Verify your LeetCode journey!", html_email)
    return "πŸ“© Verification sent"


# ================= VERIFY =================

def verify_user(token):

    conn = get_db()
    cur = conn.cursor()

    cur.execute("""
        UPDATE users
        SET email_verified=true
        WHERE verification_token=%s
        AND email_verified=false
    """, (token,))

    ok = cur.rowcount

    conn.commit()
    cur.close()
    conn.close()

    if ok == 0:
        return "❌ Invalid link"

    return "βœ… Email verified"


# ================= UNSUBSCRIBE =================

def unsubscribe_user(token):

    conn = get_db()
    cur = conn.cursor()

    cur.execute("""
        UPDATE users
        SET unsubscribed=true
        WHERE verification_token=%s
    """, (token,))

    ok = cur.rowcount

    conn.commit()
    cur.close()
    conn.close()

    if ok == 0:
        return "❌ Invalid link"

    return "βœ… Unsubscribed"


# ================= URL HANDLER =================

def handle_url(request: gr.Request):

    try:
        params = request.query_params

        if "verify" in params:
            return verify_user(params["verify"])

        if "unsubscribe" in params:
            return unsubscribe_user(params["unsubscribe"])

        return ""

    except Exception as e:
        print("URL error:", e)
        return ""



def run_scheduler(secret):

    if secret != CRON_SECRET:
        return "❌ Unauthorized"

    conn = get_db()
    cur = conn.cursor()

    cur.execute("""
        SELECT id,leetcode_username,email,timezone,
               last_sent_date,last_sent_slot,verification_token
        FROM users
        WHERE email_verified=true
        AND unsubscribed=false
    """)

    users = cur.fetchall()

    try:
        title, slug, problem_link, difficulty = get_daily_problem()
    except Exception as e:
        cur.close()
        conn.close()
        return f"❌ Failed to get daily problem: {e}"

    now = datetime.now(pytz.utc)
    sent = 0

    for uid, user, mail, tz, last_d, last_s, token in users:

        try:
            local = now.astimezone(pytz.timezone(tz))
            h = local.hour

            # Enhanced email content based on time
            if 8 <= h <= 9:
                slot = "morning"
                subject = f"πŸŒ… Today's LeetCode Challenge: {title}"
                content = f"""
                <h2 style="color: #4CAF50; margin: 0 0 15px 0;">Good morning, coder! β˜€οΈ</h2>
                <p style="color: #333; font-size: 18px; font-weight: bold; margin: 0 0 10px 0;">
                    Today's Problem: <span style="color: #4CAF50;">{title}</span>
                </p>
                <p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0;">
                    Start your day with a fresh challenge! This {difficulty} problem is perfect for warming up 
                    your coding muscles. Take your time to understand the requirements! πŸš€
                </p>
                """
                email_type = "morning"

            elif 14 <= h <= 15:
                slot = "afternoon"  
                subject = f"⏰ Afternoon Coding Break: {title}"
                content = f"""
                <h2 style="color: #FF9800; margin: 0 0 15px 0;">Time for a coding break! ⚑</h2>
                <p style="color: #333; font-size: 16px; margin: 0 0 15px 0;">
                    Haven't tackled <strong style="color: #FF9800;">{title}</strong> yet? No worries!
                </p>
                <p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0;">
                    This {difficulty} problem is waiting for you. Sometimes a fresh afternoon perspective 
                    can lead to breakthrough solutions! πŸ’‘
                </p>
                """
                email_type = "afternoon"

            elif 19 <= h <= 20:
                slot = "night"
                subject = f"πŸŒ™ Last Call: {title}"
                content = f"""
                <h2 style="color: #F44336; margin: 0 0 15px 0;">Final reminder! πŸ”₯</h2>
                <p style="color: #333; font-size: 16px; margin: 0 0 15px 0;">
                    <strong style="color: #F44336;">{title}</strong> ({difficulty}) is still waiting for you!
                </p>
                <p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
                    Don't let the day end without giving it a try. Even reading through the problem 
                    and thinking about approaches counts as progress! 
                </p>
                <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 8px;">
                    <p style="color: #856404; margin: 0; font-size: 14px;">
                        πŸ’ͺ <strong>Remember:</strong> Consistency beats perfection. Every attempt makes you stronger!
                    </p>
                </div>
                """
                email_type = "night"

            else:
                continue

            today = date.today()

            # Check if already sent today
            if last_d == today and last_s == slot:
                print(f"⏭️ Skipping {mail} - already sent {slot} email today")
                continue

            # Check if user already solved the problem
            if solved_today(user, slug):
                print(f"βœ… {user} already solved {slug} - skipping email")
                continue

            # Create beautiful HTML email with all enhancements
            html_email = create_email_template(
                title, 
                content, 
                f"{HF_URL}?unsubscribe={token}", 
                email_type,
                problem_link,
                difficulty
            )

            ok = send_email(mail, subject, html_email)

            if not ok:
                print(f"❌ Failed to send email to {mail}")
                continue

            # Update database
            cur.execute("""
                UPDATE users
                SET last_sent_date=%s,
                    last_sent_slot=%s
                WHERE id=%s
            """, (today, slot, uid))

            sent += 1

        except Exception as e:
            print(f"❌ Error processing user {user} ({mail}): {e}")
            continue

    conn.commit()
    cur.close()
    conn.close()

    return f"βœ… Scheduler completed. Sent: {sent} emails"



# ================= UI =================
with gr.Blocks(
    title="LeetCode Notifier",
    theme=gr.themes.Soft(),
    css="""
    .gradio-container {
        max-width: 800px !important;
        margin: auto !important;
    }
    """
) as app:

    gr.Markdown("""
    # πŸ“¬ LeetCode Daily Email Notifier
    
    Get personalized daily LeetCode problem reminders sent directly to your inbox! 
    Never miss a day of coding practice.
    """)

    with gr.Row():
        with gr.Column():
            u = gr.Textbox(
                label="πŸ§‘β€πŸ’» LeetCode Username", 
                placeholder="Enter your LeetCode username",
                info="We'll verify this username exists on LeetCode"
            )
            m = gr.Textbox(
                label="πŸ“§ Email Address", 
                placeholder="your.email@gmail.com",
                info="You'll receive a verification email"
            )
            tz = gr.Dropdown(
                choices=sorted(pytz.all_timezones), 
                value="Asia/Kolkata", 
                label="🌍 Timezone",
                info="Choose your timezone for proper scheduling"
            )

    with gr.Row():
        subscribe_btn = gr.Button("πŸš€ Subscribe", variant="primary", scale=2)
        
    out = gr.Textbox(label="πŸ“ Status", interactive=False, lines=2)
    
    subscribe_btn.click(subscribe, [u, m, tz], out)

    gr.Markdown("""
    ---
    ### ⏰ Email Schedule
    - **πŸŒ… 9:00 AM** - Daily problem notification
    - **πŸŒ† 3:00 PM** - Gentle reminder (if not solved)
    - **πŸŒ™ 8:00 PM** - Final reminder (if not solved)
    
    ### πŸ”’ Admin Panel
    """)

    with gr.Row():
        sec = gr.Textbox(
            label="πŸ”‘ Secret Key", 
            type="password", 
            placeholder="Enter scheduler secret key"
        )
        run_btn = gr.Button("▢️ Run Scheduler", variant="secondary")

    run_btn.click(run_scheduler, sec, out)

    # URL handler for verification/unsubscribe
    app.load(handle_url, outputs=out)


if __name__ == "__main__":
    app.launch(debug=True)