from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator


# class Senior(models.Model):
#     """Model representing a senior person who will receive calls"""
    
#     # Basic Information
#     name = models.CharField(max_length=100, help_text="Full name of the senior")
#     phone_number = models.CharField(
#         max_length=15,
#         validators=[RegexValidator(
#             regex=r'^\+?1?\d{9,15}$',
#             message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
#         )],
#         help_text="Phone number in international format (e.g., +1234567890)"
#     )
    
#     # Personal Details
#     age = models.PositiveIntegerField(null=True, blank=True, help_text="Age of the senior")
#     timezone = models.CharField(max_length=50, default='UTC', help_text="Timezone for scheduling calls")
    
#     # Preferences
#     preferred_call_times = models.JSONField(
#         default=list,
#         help_text="List of preferred call times (e.g., ['morning', 'afternoon'])"
#     )
#     interests = models.JSONField(
#         default=list,
#         help_text="List of interests and topics the senior enjoys discussing"
#     )
#     health_notes = models.TextField(
#         blank=True,
#         help_text="Any health-related notes or considerations for conversations"
#     )
    
#     # Companion Settings
#     companion_name = models.CharField(
#         max_length=100,
#         blank=True,
#         help_text="Name of the AI companion for this senior (e.g., 'Tom'). Can be used in first_message template as {companion.name}"
#     )
#     first_message = models.TextField(
#         blank=True,
#         help_text="Custom first message template for calls. Use {senior.name} for senior's name and {companion.name} for companion name. If empty, uses default greeting."
#     )
    
#     # Relationship Information
#     caregiver = models.ForeignKey(
#         User,
#         on_delete=models.CASCADE,
#         related_name='seniors',
#         help_text="The caregiver or family member managing this senior's profile"
#     )
    
#     # Metadata
#     created_at = models.DateTimeField(auto_now_add=True)
#     updated_at = models.DateTimeField(auto_now=True)
#     is_active = models.BooleanField(default=True, help_text="Whether this senior is currently active")
#     monthly_timelimit = models.PositiveIntegerField(
#         default=60,
#         help_text="Monthly call limit in minutes for this senior"
#     )
    
#     class Meta:
#         ordering = ['name']
    
#     def __str__(self):
#         return f"{self.name} ({self.phone_number})"
    
    
class Senior(models.Model):
    """Model representing a senior person who will receive calls"""
    
    # Basic Information
    name = models.CharField(max_length=100, help_text="Full name of the senior")
    phone_number = models.CharField(
        max_length=15,
        validators=[RegexValidator(
            regex=r'^\+?1?\d{9,15}$',
            message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
        )],
        help_text="Phone number in international format (e.g., +1234567890)"
    )
    
    # Personal Details
    age = models.PositiveIntegerField(null=True, blank=True, help_text="Age of the senior")
    timezone = models.CharField(max_length=50, default='UTC', help_text="Timezone for scheduling calls")
    
    # Preferences
    preferred_call_times = models.JSONField(
        default=list,
        help_text="List of preferred call times (e.g., ['morning', 'afternoon'])"
    )
    interests = models.JSONField(
        default=list,
        help_text="List of interests and topics the senior enjoys discussing"
    )
    health_notes = models.TextField(
        blank=True,
        help_text="Any health-related notes or considerations for conversations"
    )
    
    # Companion Settings
    companion_name = models.CharField(
        max_length=100,
        blank=True,
        help_text="Name of the AI companion for this senior (e.g., 'Tom'). Can be used in first_message template as {companion.name}"
    )
    first_message = models.TextField(
        blank=True,
        help_text="Custom first message template for calls. Use {senior.name} for senior's name and {companion.name} for companion name. If empty, uses default greeting."
    )
    
    # Relationship Information
    caregiver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='seniors',
        help_text="The caregiver or family member managing this senior's profile"
    )
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True, help_text="Whether this senior is currently active")
    monthly_timelimit = models.PositiveIntegerField(
        default=60,
        help_text="Monthly call allowance in minutes for this senior"
    )
    extra_minutes_balance = models.FloatField(
        default=0,
        help_text="Extra minutes balance added by admin (carried over)"
    )
    
    def get_monthly_usage_minutes(self):
        """Calculate total call duration in minutes for the current month"""
        from django.utils import timezone
        from calls.models import Call
        from django.db.models import Sum
        
        now = timezone.now()
        first_day_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        total_seconds = Call.objects.filter(
            senior=self,
            twilio_status='completed',
            call_start_time__gte=first_day_of_month
        ).aggregate(total=Sum('duration'))['total'] or 0
        
        return total_seconds / 60

    def get_available_minutes(self):
        """Calculate total available minutes (monthly allowance + extra balance - month usage)"""
        usage = self.get_monthly_usage_minutes()
        available = (self.monthly_timelimit + self.extra_minutes_balance) - usage
        return max(0, available)
    
    class Meta:
        ordering = ['name']
    
    def __str__(self):
        return f"{self.name} ({self.phone_number})"