"""Прорахунок вигоди доставки зерна від місця відвантаження до кожного місця розвантаження."""
import math
from dataclasses import dataclass, field
from decimal import Decimal, ROUND_HALF_UP

from .distances import get_distances
from .models import TransportTariff, UnloadingPointPrice

TWO_PLACES = Decimal('0.01')


def money(value):
    return value.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)


def tariff_for(km, tariffs):
    """Тариф грн/т·км для відстані. Повертає (тариф, поза_таблицею)."""
    km_whole = math.ceil(km)
    for tariff in tariffs:
        if tariff.km_from <= km_whole <= tariff.km_to:
            return tariff, False
    # Довше за найбільший діапазон таблиці — беремо останній тариф і попереджаємо
    if tariffs and km_whole > tariffs[-1].km_to:
        return tariffs[-1], True
    return None, False


@dataclass
class RouteOption:
    price: UnloadingPointPrice
    distance_km: Decimal = None
    duration_min: int = None
    rate: Decimal = None              # грн за т·км
    beyond_tariffs: bool = False
    transport_per_ton: Decimal = None
    margin_per_ton: Decimal = None    # ціна місця − ціна фермера − перевезення
    grain_total: Decimal = None
    transport_total: Decimal = None
    cost_total: Decimal = None
    revenue_total: Decimal = None
    profit_total: Decimal = None
    problem: str = ''

    @property
    def point(self):
        return self.price.unloading_point

    @property
    def available(self):
        return self.profit_total is not None

    @property
    def fca_price(self):
        """Ціна для фермера FCA: ціна місця (CPT) мінус перевезення, грн/т."""
        return self.price.price - self.transport_per_ton


@dataclass
class Calculation:
    options: list = field(default_factory=list)
    error: str = ''
    skipped_prices: int = 0           # ціни «Оновлюється»/«Стоп», які не брали до розрахунку
    grain_total: Decimal = None       # вартість зерна у фермера — однакова для всіх місць

    @property
    def best(self):
        return self.options[0] if self.options and self.options[0].available else None


def calculate(origin, culture, farmer_price, tons, farmer=None):
    """Варіанти доставки, відсортовані від найвигіднішого. Ціни — грн/т, тоннаж — т.

    origin — адреса відвантаження для Google (див. distances), farmer — для кешу відстаней господарства.
    """
    farmer_price, tons = Decimal(farmer_price), Decimal(tons)
    culture_prices = UnloadingPointPrice.objects.filter(culture=culture, unloading_point__active=True)
    prices = list(culture_prices.filter(status='active', price__isnull=False)
                  .select_related('unloading_point__region', 'unloading_point__district'))
    result = Calculation(skipped_prices=culture_prices.exclude(status='active').count(),
                         grain_total=money(farmer_price * tons))
    if not prices:
        return result

    points = list({p.unloading_point_id: p.unloading_point for p in prices}.values())
    distances, result.error = get_distances(origin, points, farmer)
    tariffs = list(TransportTariff.objects.order_by('km_from'))

    for price in prices:
        option = RouteOption(price=price)
        route = distances.get(price.unloading_point_id)
        if route is None:
            option.problem = 'Відстань ще не визначено'
        elif route.distance_km is None:
            option.problem = 'Google не знайшов маршрут до цього місця'
        else:
            option.distance_km, option.duration_min = route.distance_km, route.duration_min
            tariff, option.beyond_tariffs = tariff_for(route.distance_km, tariffs)
            if tariff is None:
                option.problem = 'Немає тарифу для цієї відстані'
            else:
                option.rate = tariff.price_per_ton_km
                option.transport_per_ton = money(option.rate * route.distance_km)
                option.margin_per_ton = money(price.price - farmer_price - option.transport_per_ton)
                option.grain_total = result.grain_total
                option.transport_total = money(option.transport_per_ton * tons)
                option.cost_total = option.grain_total + option.transport_total
                option.revenue_total = money(price.price * tons)
                option.profit_total = option.revenue_total - option.cost_total
        result.options.append(option)

    result.options.sort(key=lambda o: (not o.available, -(o.profit_total or 0), o.distance_km or 0))
    return result
