from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from farmerapp.models import Region, District, CultureableName


class TransportTariff(models.Model):
    km_from = models.PositiveIntegerField('Кілометраж від')
    km_to = models.PositiveIntegerField('До')
    price_per_ton_km = models.DecimalField('т/км', max_digits=10, decimal_places=3)
    last_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['km_from']
        verbose_name = 'Тариф на перевезення'
        verbose_name_plural = 'Тарифи на перевезення'

    def clean(self):
        if self.km_from is not None and self.km_to is not None and self.km_from > self.km_to:
            raise ValidationError('"Кілометраж від" не може бути більшим за "До".')

    def __str__(self):
        return f"{self.km_from}–{self.km_to} км: {self.price_per_ton_km}"

    @classmethod
    def for_distance(cls, km):
        return cls.objects.filter(km_from__lte=km, km_to__gte=km).first()


class TariffImport(models.Model):
    """Історія повних замін таблиці тарифів; останнє посилання на Google Таблицю підставляється у форму."""

    created_at = models.DateTimeField('Час', auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, verbose_name='Хто')
    source = models.CharField('Джерело', max_length=500)
    sheet_url = models.URLField('Google Таблиця', max_length=500, blank=True)
    old_count = models.PositiveIntegerField('Було рядків')
    new_count = models.PositiveIntegerField('Стало рядків')

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Імпорт тарифів'
        verbose_name_plural = 'Імпорти тарифів'

    def __str__(self):
        return f'{self.created_at:%d.%m.%Y %H:%M}: {self.source}'


class UnloadingPointImport(models.Model):
    """Історія повних оновлень місць розвантаження з таблиці."""

    created_at = models.DateTimeField('Час', auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, verbose_name='Хто')
    source = models.CharField('Джерело', max_length=500)
    sheet_url = models.URLField('Google Таблиця', max_length=500, blank=True)
    created = models.PositiveIntegerField('Додано місць')
    updated = models.PositiveIntegerField('Змінено місць')
    deleted = models.PositiveIntegerField('Видалено місць')
    deleted_names = models.TextField('Видалені місця', blank=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Імпорт місць розвантаження'
        verbose_name_plural = 'Імпорти місць розвантаження'

    def __str__(self):
        return f'{self.created_at:%d.%m.%Y %H:%M}: {self.source}'


class UnloadingPoint(models.Model):
    name = models.CharField('Назва', max_length=255)
    region = models.ForeignKey(Region, on_delete=models.PROTECT, verbose_name='Область', related_name='unloading_points')
    district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Район', related_name='unloading_points')
    settlement = models.CharField('Населений пункт', max_length=255, blank=True)
    terminal = models.CharField('Термінал / покупець', max_length=255, blank=True)
    latitude = models.DecimalField('Широта', max_digits=9, decimal_places=6, null=True, blank=True)
    longitude = models.DecimalField('Довгота', max_digits=9, decimal_places=6, null=True, blank=True)
    active = models.BooleanField('Активне', default=True)
    comment = models.TextField('Коментар', blank=True)
    last_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['region__name', 'name']
        verbose_name = 'Місце розвантаження'
        verbose_name_plural = 'Місця розвантаження'

    def clean(self):
        if self.district_id and self.region_id and self.district.region_id != self.region_id:
            raise ValidationError({'district': 'Район не належить вибраній області.'})
        if (self.latitude is None) != (self.longitude is None):
            raise ValidationError('Вкажіть і широту, і довготу, або залиште обидва поля порожніми.')

    def __str__(self):
        return f"{self.name} ({self.region})"


class UnloadingPointPrice(models.Model):
    STATUS_CHOICES = [
        ('active', 'Актуальна'),
        ('updating', 'Оновлюється'),
        ('stop', 'Стоп'),
    ]

    unloading_point = models.ForeignKey(UnloadingPoint, on_delete=models.CASCADE, related_name='prices', verbose_name='Місце розвантаження')
    culture = models.ForeignKey(CultureableName, on_delete=models.PROTECT, related_name='unloading_prices', verbose_name='Культура')
    specification = models.CharField('Клас / специфікація', max_length=255, blank=True,
                                     help_text='Напр. "2 клас", "11 білок ДСТУ", "ГМО"')
    price = models.DecimalField('Ціна закупівлі, грн з ПДВ за т', max_digits=12, decimal_places=2, null=True, blank=True)
    status = models.CharField('Статус', max_length=20, choices=STATUS_CHOICES, default='active')
    last_updated = models.DateTimeField('Оновлено', auto_now=True)

    class Meta:
        ordering = ['culture__cultureable_name', 'specification']
        verbose_name = 'Ціна культури'
        verbose_name_plural = 'Ціни культур'
        constraints = [
            models.UniqueConstraint(fields=['unloading_point', 'culture', 'specification'], name='unique_point_culture_spec'),
        ]

    def clean(self):
        if self.status == 'active' and self.price is None:
            raise ValidationError({'price': 'Вкажіть ціну або змініть статус.'})

    def __str__(self):
        spec = f" {self.specification}" if self.specification else ''
        return f"{self.culture}{spec} — {self.price or self.get_status_display()}"


class RouteDistance(models.Model):
    """Кеш відстаней дорогами від господарства або населеного пункту до місця розвантаження (Google Routes API)."""
    # Порожнє — відстань від населеного пункту, обраного в калькуляторі; тоді кеш шукається за origin
    farmer = models.ForeignKey('farmerapp.Farmer', on_delete=models.CASCADE, related_name='route_distances',
                               null=True, blank=True)
    unloading_point = models.ForeignKey(UnloadingPoint, on_delete=models.CASCADE, related_name='route_distances')
    # Адреси, за якими рахувалась відстань: якщо адреса змінилась, відстань перераховується
    origin = models.CharField(max_length=1000)
    destination = models.CharField(max_length=1000)
    distance_km = models.DecimalField(max_digits=8, decimal_places=1, null=True, blank=True)
    duration_min = models.PositiveIntegerField(null=True, blank=True)
    fetched_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['farmer', 'unloading_point'], name='unique_farmer_point_distance'),
        ]
        verbose_name = 'Відстань до місця розвантаження'
        verbose_name_plural = 'Відстані до місць розвантаження'

    def __str__(self):
        return f"{self.farmer or self.origin} → {self.unloading_point}: {self.distance_km} км"
