import datetime

from django.db.models import Q, Sum
from django.db.models.functions import Abs, Greatest, TruncMonth


def history(transaction_set):
    if not transaction_set.exists():
        return None

    _transaction_month = transaction_set.values(month=TruncMonth("date")).order_by(
        "-date"
    )
    _first_month = _transaction_month.last()["month"]
    _last_month = _transaction_month.first()["month"]

    _history = (
        _transaction_month.annotate(
            sum_p=Sum("value", filter=Q(value__gt=0), default=0),
            sum_m=Sum("value", filter=Q(value__lt=0), default=0),
            sum=Sum("value"),
        )
        .annotate(max_sum=Greatest("sum_p", Abs("sum_m")))
        .order_by("-month")
    )

    _data = [
        _history.filter(month=datetime.date(y, m + 1, 1)).first()
        or {"month": datetime.date(y, m + 1, 1), "sum": None}
        for y in range(
            _first_month.year,
            _last_month.year + 1,
        )
        for m in range(
            _first_month.month - 1 if _first_month.year == y else 0,
            _last_month.month if _last_month.year == y else 12,
        )
    ]

    return {
        "data": _data,
        "max": {
            "pm": 125
            * _history.order_by("-max_sum")[len(_history.exclude(max_sum=0)) // 10][
                "max_sum"
            ]
            / 100,
            "sum": 125
            * _history.annotate(abs_sum=Abs("sum")).order_by("-abs_sum")[
                len(_history) // 10
            ]["abs_sum"]
            / 100,
        },
    }
