from datetime import date
import re
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from apps.communications.hooks import queue_appointment_reminders
from apps.communications.models import NotificationTemplate


class Command(BaseCommand):
    help = "Queue eligible appointment reminders only; does not dispatch or schedule messages."

    def add_arguments(self, parser):
        for name in ("actor", "template", "date", "policy"):
            parser.add_argument("--" + name, required=True)

    def handle(self, *args, **options):
        try:
            if not re.fullmatch(r"[a-zA-Z0-9_-]{1,64}", options["policy"]):
                raise ValueError
            actor = get_user_model().objects.get(pk=options["actor"])
            template = NotificationTemplate.objects.get(pk=options["template"])
            rows = queue_appointment_reminders(actor=actor, template=template,
                date=date.fromisoformat(options["date"]), policy=options["policy"])
        except Exception:
            raise CommandError("Reminder preparation failed; check inputs, permissions and template/contact configuration.") from None
        self.stdout.write(f"Eligible notification records: {len(rows)} (existing idempotent records included). No messages dispatched.")
