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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
import asyncio
import json
import logging
import os
import re
import sys
import time
from threading import Thread
from typing import Any, Dict, List, Literal, Optional, Tuple, Union

import discord
from discord.abc import Messageable
from discord.ext import commands

try:
    from flask import Flask
except ImportError:
    Flask = None

try:
    from dotenv import load_dotenv
except ImportError:
    def load_dotenv(*_args: Any, **_kwargs: Any) -> bool:
        return False

DURATION_PATTERN = re.compile(r"^(\d+)\s*([^\W\d_]+)$")
UNIT_ALIASES: Dict[str, str] = {
    "s": "s",
    "sec": "s",
    "secs": "s",
    "second": "s",
    "seconds": "s",
    "giay": "s",
    "giây": "s",
    "m": "m",
    "min": "m",
    "mins": "m",
    "minute": "m",
    "minutes": "m",
    "phut": "m",
    "phút": "m",
    "h": "h",
    "hr": "h",
    "hrs": "h",
    "hour": "h",
    "hours": "h",
    "gio": "h",
    "giờ": "h",
}
ReminderKey = Tuple[int, str]
ReminderRow = Dict[str, Union[int, str]]
DeliveryResult = Literal["sent", "transient_failure", "permanent_failure"]
LOCAL_CONFIG_PATH = "bot_config.json"
LOCAL_CONFIG_KEYS = (
    "DISCORD_BOT_TOKEN",
    "COMMAND_PREFIX",
    "STORAGE_PATH",
    "TRIGGER_DEBOUNCE_SECONDS",
    "REMINDER_RETRY_SECONDS",
    "RESTART_DELAY_SECONDS",
    "LOG_LEVEL",
)


def get_env_int(name: str, default: int, min_value: Optional[int] = None) -> int:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default

    try:
        value = int(raw_value)
    except ValueError:
        logging.warning("Invalid %s=%s. Using default=%s", name, raw_value, default)
        return default

    if min_value is not None and value < min_value:
        logging.warning(
            "%s=%s is below minimum %s. Using %s.",
            name,
            value,
            min_value,
            min_value,
        )
        return min_value

    return value


def get_env_float(name: str, default: float, min_value: Optional[float] = None) -> float:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default

    try:
        value = float(raw_value)
    except ValueError:
        logging.warning("Invalid %s=%s. Using default=%s", name, raw_value, default)
        return default

    if min_value is not None and value < min_value:
        logging.warning(
            "%s=%s is below minimum %s. Using %s.",
            name,
            value,
            min_value,
            min_value,
        )
        return min_value

    return value


def should_start_keepalive_server() -> bool:
    raw_value = os.getenv("ENABLE_KEEPALIVE_SERVER", "1")
    return raw_value.strip().lower() not in {"0", "false", "no", "off"}


def start_keepalive_server() -> None:
    if not should_start_keepalive_server():
        logging.info("Keep-alive web server is disabled.")
        return

    if Flask is None:
        logging.warning(
            "Flask is not installed. Keep-alive web server is skipped. Install requirements to enable it."
        )
        return

    host = os.getenv("KEEPALIVE_HOST", "0.0.0.0")
    port = get_env_int("PORT", default=7860, min_value=1)
    app = Flask("reminder_bot_keepalive")

    @app.get("/")
    def index() -> str:
        return "Reminder Discord Bot is running."

    @app.get("/health")
    def health() -> Dict[str, str]:
        return {"status": "ok", "service": "reminder-discord-bot"}

    def run_server() -> None:
        app.run(host=host, port=port, debug=False, use_reloader=False)

    Thread(target=run_server, name="keepalive-server", daemon=True).start()
    logging.info("Keep-alive web server started at http://%s:%s", host, port)


def load_local_config(config_path: str) -> Dict[str, str]:
    if not os.path.exists(config_path):
        return {}

    try:
        with open(config_path, "r", encoding="utf-8") as file_handle:
            raw_config = json.load(file_handle)
    except (OSError, json.JSONDecodeError):
        logging.exception("Failed to read %s. Ignoring local config.", config_path)
        return {}

    if not isinstance(raw_config, dict):
        logging.warning("Invalid %s format. Expected a JSON object.", config_path)
        return {}

    normalized: Dict[str, str] = {}
    for key in LOCAL_CONFIG_KEYS:
        value = raw_config.get(key)
        if value is None:
            continue

        if isinstance(value, (str, int, float)):
            normalized[key] = str(value).strip()
            continue

        logging.warning("Ignoring %s in %s due to unsupported type.", key, config_path)

    return normalized


def save_local_config(config_path: str, config_values: Dict[str, str]) -> None:
    config_dir = os.path.dirname(os.path.abspath(config_path))
    if config_dir:
        os.makedirs(config_dir, exist_ok=True)

    payload = {
        key: value
        for key, value in config_values.items()
        if key in LOCAL_CONFIG_KEYS and value
    }

    temp_path = f"{config_path}.tmp"
    with open(temp_path, "w", encoding="utf-8") as file_handle:
        json.dump(payload, file_handle, ensure_ascii=True, indent=2)

    os.replace(temp_path, config_path)


def apply_local_config(config_values: Dict[str, str]) -> None:
    for key, value in config_values.items():
        if value:
            os.environ.setdefault(key, value)


def resolve_bot_token(config_path: str, config_values: Dict[str, str]) -> str:
    token = os.getenv("DISCORD_BOT_TOKEN", "").strip()
    if token:
        return token

    if not sys.stdin or not sys.stdin.isatty():
        return ""

    print("DISCORD_BOT_TOKEN chưa được cấu hình.")
    print(f"Nhập token để lưu vào {config_path} (chỉ cần 1 lần).")
    provided_token = input("Token: ").strip()
    if not provided_token:
        return ""

    config_values["DISCORD_BOT_TOKEN"] = provided_token
    save_local_config(config_path, config_values)
    os.environ["DISCORD_BOT_TOKEN"] = provided_token
    print(f"Đã lưu token vào {config_path}.")
    return provided_token


def parse_duration(duration_text: str) -> int:
    normalized_input = duration_text.strip().lower()
    match = DURATION_PATTERN.match(normalized_input)
    if not match:
        raise ValueError(
            "Định dạng thời gian không hợp lệ. Ví dụ: 30s, 12m, 2h, 30 sec, 15 phút, 1 giờ"
        )

    value = int(match.group(1))
    raw_unit = match.group(2)
    unit = UNIT_ALIASES.get(raw_unit)
    if unit is None:
        raise ValueError(
            "Đơn vị thời gian không hợp lệ. Dùng s/sec/giây, m/min/phút, h/hr/giờ."
        )

    if value <= 0:
        raise ValueError("Thời gian phải lớn hơn 0.")

    multiplier = {"s": 1, "m": 60, "h": 3600}[unit]
    return value * multiplier


def format_duration(seconds: int) -> str:
    seconds = max(0, seconds)
    hours, remainder = divmod(seconds, 3600)
    minutes, sec = divmod(remainder, 60)

    parts: List[str] = []
    if hours:
        parts.append(f"{hours}h")
    if minutes:
        parts.append(f"{minutes}m")
    if sec or not parts:
        parts.append(f"{sec}s")

    return " ".join(parts)


class ReminderRepository:
    def __init__(self, storage_path: str) -> None:
        self.storage_path = storage_path
        self.is_memory_only = storage_path == ":memory:"
        self._lock = asyncio.Lock()
        self._initialized = False
        self._state: Dict[str, Dict[str, ReminderRow]] = self._default_state()

    @staticmethod
    def _default_state() -> Dict[str, Dict[str, ReminderRow]]:
        return {"configs": {}, "active_reminders": {}}

    @staticmethod
    def _make_key(user_id: int, trigger_word: str) -> str:
        return f"{user_id}:{trigger_word}"

    def _normalize_state(self, raw: Any) -> Dict[str, Dict[str, ReminderRow]]:
        normalized = self._default_state()
        if not isinstance(raw, dict):
            return normalized

        for bucket_name in ("configs", "active_reminders"):
            bucket_value = raw.get(bucket_name)
            if not isinstance(bucket_value, dict):
                continue

            for raw_key, raw_row in bucket_value.items():
                if not isinstance(raw_key, str) or not isinstance(raw_row, dict):
                    continue

                try:
                    user_id = int(raw_row["user_id"])
                    trigger_word = str(raw_row["trigger_word"])
                    channel_id = int(raw_row["channel_id"])

                    row: ReminderRow = {
                        "user_id": user_id,
                        "trigger_word": trigger_word,
                        "channel_id": channel_id,
                    }

                    if bucket_name == "configs":
                        row["duration_seconds"] = int(raw_row["duration_seconds"])
                    else:
                        row["due_at"] = int(raw_row["due_at"])
                except (KeyError, TypeError, ValueError):
                    continue

                normalized[bucket_name][raw_key] = row

        return normalized

    def _ensure_storage_dir(self) -> None:
        if self.is_memory_only:
            return

        directory = os.path.dirname(os.path.abspath(self.storage_path))
        if directory:
            os.makedirs(directory, exist_ok=True)

    def _read_from_disk(self) -> None:
        if self.is_memory_only:
            self._state = self._default_state()
            return

        self._ensure_storage_dir()
        if not os.path.exists(self.storage_path):
            self._state = self._default_state()
            self._write_to_disk(self._state)
            return

        try:
            with open(self.storage_path, "r", encoding="utf-8") as file_handle:
                loaded = json.load(file_handle)
        except (OSError, json.JSONDecodeError):
            logging.exception("Failed to read storage file %s. Resetting state.", self.storage_path)
            self._state = self._default_state()
            self._write_to_disk(self._state)
            return

        self._state = self._normalize_state(loaded)

    def _write_to_disk(self, state: Dict[str, Dict[str, ReminderRow]]) -> None:
        if self.is_memory_only:
            return

        self._ensure_storage_dir()
        temp_path = f"{self.storage_path}.tmp"
        with open(temp_path, "w", encoding="utf-8") as file_handle:
            json.dump(state, file_handle, ensure_ascii=True, indent=2)

        os.replace(temp_path, self.storage_path)

    async def _ensure_initialized(self) -> None:
        if self._initialized:
            return

        async with self._lock:
            if self._initialized:
                return

            await asyncio.to_thread(self._read_from_disk)
            self._initialized = True

    async def _persist_locked(self) -> None:
        await asyncio.to_thread(self._write_to_disk, self._state)

    async def init_schema(self) -> None:
        await self._ensure_initialized()

    async def upsert_config(
        self, user_id: int, trigger_word: str, duration_seconds: int, channel_id: int
    ) -> None:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            self._state["configs"][key] = {
                "user_id": user_id,
                "trigger_word": trigger_word,
                "duration_seconds": duration_seconds,
                "channel_id": channel_id,
            }
            await self._persist_locked()

    async def get_config(self, user_id: int, trigger_word: str) -> Optional[ReminderRow]:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            row = self._state["configs"].get(key)
            if row is None:
                return None
            return dict(row)

    async def list_configs(self, user_id: int) -> List[ReminderRow]:
        await self._ensure_initialized()
        async with self._lock:
            rows = [
                dict(row)
                for row in self._state["configs"].values()
                if int(row["user_id"]) == user_id
            ]

        rows.sort(key=lambda item: str(item["trigger_word"]))
        return rows

    async def delete_config(self, user_id: int, trigger_word: str) -> bool:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            removed = self._state["configs"].pop(key, None) is not None
            if removed:
                await self._persist_locked()
            return removed

    async def upsert_active_reminder(
        self, user_id: int, trigger_word: str, due_at: int, channel_id: int
    ) -> None:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            self._state["active_reminders"][key] = {
                "user_id": user_id,
                "trigger_word": trigger_word,
                "due_at": due_at,
                "channel_id": channel_id,
            }
            await self._persist_locked()

    async def get_active_reminder(
        self, user_id: int, trigger_word: str
    ) -> Optional[ReminderRow]:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            row = self._state["active_reminders"].get(key)
            if row is None:
                return None
            return dict(row)

    async def list_active_for_user(self, user_id: int) -> List[ReminderRow]:
        await self._ensure_initialized()
        async with self._lock:
            rows = [
                dict(row)
                for row in self._state["active_reminders"].values()
                if int(row["user_id"]) == user_id
            ]

        rows.sort(key=lambda item: str(item["trigger_word"]))
        return rows

    async def list_all_active_reminders(self) -> List[ReminderRow]:
        await self._ensure_initialized()
        async with self._lock:
            rows = [dict(row) for row in self._state["active_reminders"].values()]

        rows.sort(key=lambda item: (int(item["due_at"]), str(item["trigger_word"])))
        return rows

    async def delete_active_reminder(self, user_id: int, trigger_word: str) -> bool:
        await self._ensure_initialized()
        async with self._lock:
            key = self._make_key(user_id, trigger_word)
            removed = self._state["active_reminders"].pop(key, None) is not None
            if removed:
                await self._persist_locked()
            return removed


class ReminderCog(commands.Cog):
    def __init__(self, bot: commands.Bot, repo: ReminderRepository) -> None:
        self.bot = bot
        self.repo = repo
        self.debounce_seconds = get_env_float(
            "TRIGGER_DEBOUNCE_SECONDS", default=1.0, min_value=0.0
        )
        self.retry_seconds = get_env_int(
            "REMINDER_RETRY_SECONDS", default=30, min_value=5
        )
        self.active_tasks: Dict[ReminderKey, asyncio.Task[None]] = {}
        self.last_trigger_seen: Dict[ReminderKey, float] = {}
        self.schedule_lock = asyncio.Lock()
        self._restored_once = False

    @commands.Cog.listener()
    async def on_ready(self) -> None:
        if not self._restored_once:
            await self.restore_pending_reminders()
            self._restored_once = True

        if self.bot.user is not None:
            logging.info("Bot is online as %s", self.bot.user)

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if message.author.bot:
            return

        content = message.content.strip()
        if not content:
            return

        if self._is_command_message(content):
            return

        config = await self.repo.get_config(message.author.id, content)
        if config is None:
            return

        key = (message.author.id, content)
        now_mono = time.monotonic()
        last_seen = self.last_trigger_seen.get(key)

        if last_seen is not None and (now_mono - last_seen) < self.debounce_seconds:
            return

        self.last_trigger_seen[key] = now_mono

        duration_seconds = int(config["duration_seconds"])
        channel_id = int(config["channel_id"])
        await self.start_or_reset_reminder(
            user_id=message.author.id,
            trigger_word=content,
            duration_seconds=duration_seconds,
            channel_id=channel_id,
        )

    def _is_command_message(self, content: str) -> bool:
        prefix = self.bot.command_prefix

        if isinstance(prefix, str):
            return content.startswith(prefix)

        if isinstance(prefix, (list, tuple)):
            return any(content.startswith(str(item)) for item in prefix)

        return False

    async def start_or_reset_reminder(
        self, user_id: int, trigger_word: str, duration_seconds: int, channel_id: int
    ) -> None:
        due_at = int(time.time()) + duration_seconds
        await self.repo.upsert_active_reminder(
            user_id=user_id,
            trigger_word=trigger_word,
            due_at=due_at,
            channel_id=channel_id,
        )
        await self.schedule_task(user_id, trigger_word, due_at, channel_id)
        logging.info(
            "Reminder scheduled user=%s trigger=%s due_at=%s",
            user_id,
            trigger_word,
            due_at,
        )

    async def schedule_task(
        self, user_id: int, trigger_word: str, due_at: int, channel_id: int
    ) -> None:
        key: ReminderKey = (user_id, trigger_word)
        task = asyncio.create_task(
            self.reminder_worker(user_id, trigger_word, due_at, channel_id)
        )

        async with self.schedule_lock:
            old_task = self.active_tasks.get(key)
            self.active_tasks[key] = task

        if (
            old_task is not None
            and old_task is not asyncio.current_task()
            and not old_task.done()
        ):
            old_task.cancel()

    async def cancel_task(self, key: ReminderKey) -> bool:
        async with self.schedule_lock:
            task = self.active_tasks.pop(key, None)

        if task is None:
            return False

        if not task.done():
            task.cancel()

        return True

    async def shutdown(self) -> None:
        async with self.schedule_lock:
            tasks = list(self.active_tasks.values())
            self.active_tasks.clear()

        for task in tasks:
            if not task.done():
                task.cancel()

        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)

    async def process_due_reminder(
        self, user_id: int, trigger_word: str, channel_id: int
    ) -> Literal["resolved", "rescheduled"]:
        result = await self.send_reminder(user_id, trigger_word, channel_id)

        if result == "transient_failure":
            retry_due_at = int(time.time()) + self.retry_seconds
            await self.repo.upsert_active_reminder(
                user_id=user_id,
                trigger_word=trigger_word,
                due_at=retry_due_at,
                channel_id=channel_id,
            )
            await self.schedule_task(user_id, trigger_word, retry_due_at, channel_id)
            logging.warning(
                "Transient reminder failure user=%s trigger=%s. Retry in %s seconds.",
                user_id,
                trigger_word,
                self.retry_seconds,
            )
            return "rescheduled"

        await self.repo.delete_active_reminder(user_id, trigger_word)
        return "resolved"

    async def reminder_worker(
        self, user_id: int, trigger_word: str, due_at: int, channel_id: int
    ) -> None:
        key: ReminderKey = (user_id, trigger_word)

        try:
            wait_seconds = max(0, due_at - int(time.time()))
            await asyncio.sleep(wait_seconds)

            row = await self.repo.get_active_reminder(user_id, trigger_word)
            if row is None:
                return

            if int(row["due_at"]) != due_at:
                return

            await self.process_due_reminder(user_id, trigger_word, channel_id)
        except asyncio.CancelledError:
            return
        except Exception:
            logging.exception(
                "Unexpected error in reminder worker user=%s trigger=%s",
                user_id,
                trigger_word,
            )
        finally:
            async with self.schedule_lock:
                current_task = self.active_tasks.get(key)
                if current_task is asyncio.current_task():
                    self.active_tasks.pop(key, None)

    async def send_reminder(
        self, user_id: int, trigger_word: str, channel_id: int
    ) -> DeliveryResult:
        channel = self.bot.get_channel(channel_id)

        if channel is None:
            try:
                channel = await self.bot.fetch_channel(channel_id)
            except (discord.NotFound, discord.Forbidden):
                logging.warning(
                    "Cannot fetch channel=%s for user=%s trigger=%s",
                    channel_id,
                    user_id,
                    trigger_word,
                )
                return "permanent_failure"
            except discord.HTTPException:
                logging.exception(
                    "Transient channel fetch error channel=%s user=%s trigger=%s",
                    channel_id,
                    user_id,
                    trigger_word,
                )
                return "transient_failure"

        if not isinstance(channel, Messageable):
            logging.warning(
                "Channel id=%s is not messageable for trigger=%s", channel_id, trigger_word
            )
            return "permanent_failure"

        text = f"Alo em <@{user_id}> hả em, đến lúc [{trigger_word}] rồi!"

        try:
            await channel.send(text)
            return "sent"
        except (discord.NotFound, discord.Forbidden):
            logging.warning(
                "Cannot send reminder due to channel access user=%s trigger=%s channel=%s",
                user_id,
                trigger_word,
                channel_id,
            )
            return "permanent_failure"
        except discord.HTTPException:
            logging.exception(
                "Failed to send reminder user=%s trigger=%s channel=%s",
                user_id,
                trigger_word,
                channel_id,
            )
            return "transient_failure"

    async def restore_pending_reminders(self) -> None:
        rows = await self.repo.list_all_active_reminders()
        if not rows:
            return

        now = int(time.time())
        resolved = 0
        rescheduled = 0
        retried = 0

        for row in rows:
            user_id = int(row["user_id"])
            trigger_word = str(row["trigger_word"])
            due_at = int(row["due_at"])
            channel_id = int(row["channel_id"])

            if due_at <= now:
                outcome = await self.process_due_reminder(
                    user_id, trigger_word, channel_id
                )
                if outcome == "resolved":
                    resolved += 1
                else:
                    retried += 1
                continue

            await self.schedule_task(user_id, trigger_word, due_at, channel_id)
            rescheduled += 1

        logging.info(
            "Restore finished resolved=%s rescheduled=%s retried=%s",
            resolved,
            rescheduled,
            retried,
        )

    @commands.command(name="set_remind")
    async def set_remind(
        self, ctx: commands.Context[commands.Bot], trigger_word: str, duration_text: str
    ) -> None:
        if len(trigger_word) > 64:
            await ctx.send("Trigger quá dài. Giới hạn: 64 ký tự.")
            return

        try:
            duration_seconds = parse_duration(duration_text)
        except ValueError as exc:
            await ctx.send(str(exc))
            return

        await self.repo.upsert_config(
            user_id=ctx.author.id,
            trigger_word=trigger_word,
            duration_seconds=duration_seconds,
            channel_id=ctx.channel.id,
        )

        await ctx.send(
            "Đã thiết lập. Tôi sẽ nhắc bạn "
            f"{format_duration(duration_seconds)} sau khi bạn gõ '{trigger_word}'."
        )

    @commands.command(name="list_remind")
    async def list_remind(self, ctx: commands.Context[commands.Bot]) -> None:
        configs = await self.repo.list_configs(ctx.author.id)
        if not configs:
            await ctx.send("Bạn chưa có reminder nào.")
            return

        active_rows = await self.repo.list_active_for_user(ctx.author.id)
        active_map = {str(row["trigger_word"]): int(row["due_at"]) for row in active_rows}

        now = int(time.time())
        lines: List[str] = []
        for item in configs:
            trigger_word = str(item["trigger_word"])
            duration_seconds = int(item["duration_seconds"])
            channel_id = int(item["channel_id"])

            due_at = active_map.get(trigger_word)
            if due_at is None:
                status = "idle"
            else:
                remaining = max(0, due_at - now)
                status = f"active (còn {format_duration(remaining)})"

            lines.append(
                f"- [{trigger_word}] {format_duration(duration_seconds)} | {status} | channel <#{channel_id}>"
            )

        await ctx.send("Danh sách reminder:\n" + "\n".join(lines))

    @commands.command(name="remove_remind")
    async def remove_remind(
        self, ctx: commands.Context[commands.Bot], trigger_word: str
    ) -> None:
        config_removed = await self.repo.delete_config(ctx.author.id, trigger_word)
        active_removed = await self.repo.delete_active_reminder(ctx.author.id, trigger_word)
        await self.cancel_task((ctx.author.id, trigger_word))
        self.last_trigger_seen.pop((ctx.author.id, trigger_word), None)

        if not config_removed and not active_removed:
            await ctx.send(f"Không tìm thấy trigger [{trigger_word}].")
            return

        if active_removed:
            await ctx.send(f"Đã xóa trigger [{trigger_word}] và hủy timer đang chạy.")
            return

        await ctx.send(f"Đã xóa trigger [{trigger_word}].")

    @commands.Cog.listener()
    async def on_command_error(
        self, ctx: commands.Context[commands.Bot], error: commands.CommandError
    ) -> None:
        if isinstance(error, commands.CommandNotFound):
            return

        if isinstance(error, commands.MissingRequiredArgument) and ctx.command is not None:
            usage = f"{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}".strip()
            await ctx.send(f"Thiếu tham số. Cách dùng: {usage}")
            return

        if isinstance(error, commands.BadArgument):
            await ctx.send("Tham số không hợp lệ.")
            return

        logging.exception("Unhandled command error", exc_info=error)
        await ctx.send("Có lỗi xảy ra khi xử lý lệnh.")


class TriggerReminderBot(commands.Bot):
    def __init__(self, command_prefix: str, storage_path: str, proxy_url: Optional[str] = None) -> None:
        intents = discord.Intents.default()
        intents.message_content = True
        # Thêm proxy=proxy_url vào super().__init__
        super().__init__(command_prefix=command_prefix, intents=intents, proxy=proxy_url) 

        self.repo = ReminderRepository(storage_path)
        self.reminder_cog = ReminderCog(self, self.repo)

    async def setup_hook(self) -> None:
        await self.repo.init_schema()
        await self.add_cog(self.reminder_cog)

    async def close(self) -> None:
        await self.reminder_cog.shutdown()

        await super().close()


def main() -> None:
    load_dotenv()

    config_path = os.getenv("BOT_CONFIG_PATH", LOCAL_CONFIG_PATH)
    local_config = load_local_config(config_path)
    apply_local_config(local_config)

    token = resolve_bot_token(config_path, local_config)
    if not token:
        raise SystemExit(
            "Missing DISCORD_BOT_TOKEN. Set env/.env or run py bot.py in terminal to enter and save token."
        )

    command_prefix = os.getenv("COMMAND_PREFIX", "!")
    storage_path = os.getenv("STORAGE_PATH", "data/reminder_data.json")
    log_level = os.getenv("LOG_LEVEL", "INFO").upper()
    restart_delay_seconds = get_env_int(
        "RESTART_DELAY_SECONDS", default=15, min_value=5
    )

    if storage_path != ":memory:":
        storage_dir = os.path.dirname(os.path.abspath(storage_path))
        os.makedirs(storage_dir, exist_ok=True)

    logging.basicConfig(
        level=getattr(logging, log_level, logging.INFO),
        format="%(asctime)s [%(levelname)s] %(message)s",
    )
    start_keepalive_server()

    while True:
        proxy_from_env = os.getenv("PROXY_URL")
        bot = TriggerReminderBot(command_prefix=command_prefix, storage_path=storage_path,proxy_url=proxy_from_env)
        try:
            bot.run(token, reconnect=True, log_handler=None)
            break
        except discord.LoginFailure as exc:
            raise SystemExit("Invalid DISCORD_BOT_TOKEN.") from exc
        except KeyboardInterrupt:
            logging.info("Shutdown requested by user.")
            break
        except Exception:
            logging.exception(
                "Bot crashed unexpectedly. Restarting in %s seconds.",
                restart_delay_seconds,
            )
            time.sleep(restart_delay_seconds)


if __name__ == "__main__":
    main()