from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver


def user_profile_upload_path(instance, filename):
    # Files will be uploaded to MEDIA_ROOT/profile_pics/user_<id>/<filename>
    return f'profile_pics/user_{instance.user.id}/{filename}'


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    bio = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to=user_profile_upload_path, blank=True, null=True)
    is_seller = models.BooleanField(default=False)
    phone = models.CharField(max_length=30, blank=True, default='')
    location_label = models.CharField(max_length=255, blank=True, default='')
    default_address = models.TextField(blank=True, default='')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)
    location_accuracy_m = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    location_updated_at = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return f'Profile for {self.user.username}'

    @property
    def short_location(self):
        if self.location_label and self.location_label.strip():
            return self.location_label.strip()
        if self.default_address and self.default_address.strip():
            return self.default_address.splitlines()[0].strip()
        return ''

    @property
    def formatted_delivery_address(self):
        return (self.default_address or '').strip()

    @property
    def has_precise_location(self):
        return self.latitude is not None and self.longitude is not None


@receiver(post_save, sender=User)
def ensure_profile_exists(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    else:
        # save existing profile to ensure any related signals run
        try:
            instance.profile.save()
        except Exception:
            pass
