"""Idempotent financial setup; no wallet credit or sporting-state mutation."""
from datetime import datetime,timedelta,time
from decimal import Decimal
from django.db import transaction
from django.utils import timezone

from .models import AccountingPeriod,ClubBudget,BudgetLine,FFPPolicy
from .constants import BudgetStatus


@transaction.atomic
def prepare_club(club, *, at=None):
    from clubs.models import Club
    club=Club.objects.select_for_update().get(pk=club.pk)
    at=at or timezone.now()
    from seasons.models import Season
    from django.db.models import Q
    season=Season.objects.filter(start_date__lte=timezone.localtime(at).date(),end_date__gte=timezone.localtime(at).date()).filter(
        Q(status='ACTIVE')|Q(automation__enabled=True)).order_by('-start_date').first()
    upcoming=Season.objects.filter(start_date__gt=timezone.localtime(at).date(),automation__enabled=True).order_by('start_date').first()
    period=AccountingPeriod.objects.filter(club=club,starts_at__lte=at,ends_at__gt=at).first()
    if period and not period.is_closed and period.name.startswith('Operating ') and upcoming:
        boundary=timezone.make_aware(datetime.combine(upcoming.start_date,time.min))
        if boundary < period.ends_at:
            period.ends_at=boundary;period.save(update_fields=['ends_at'])
    if not period:
        start=timezone.make_aware(datetime(at.year,1,1)); end=timezone.make_aware(datetime(at.year+1,1,1))
        if season:
            start=timezone.make_aware(datetime.combine(season.start_date,time.min))
            end=timezone.make_aware(datetime.combine(season.end_date+timedelta(days=1),time.min))
        elif upcoming:
            end=min(end,timezone.make_aware(datetime.combine(upcoming.start_date,time.min)))
        previous=AccountingPeriod.objects.filter(club=club,ends_at__lte=at).order_by('-ends_at').first()
        following=AccountingPeriod.objects.filter(club=club,starts_at__gt=at).order_by('starts_at').first()
        if previous: start=max(start,previous.ends_at)
        if following: end=min(end,following.starts_at)
        period=AccountingPeriod.objects.create(club=club,season=season,name=f'Operating {at.year} {start.date()}',starts_at=start,ends_at=end)
    elif season and not period.season_id and not period.is_closed and period.name.startswith('Operating '):
        period.season=season;period.save(update_fields=['season'])
    if period.is_closed:
        return period
    budget=ClubBudget.objects.filter(club=club,period=period,status=BudgetStatus.ACTIVE).first()
    if not budget:
        budget=ClubBudget.objects.create(club=club,period=period,name='Amateur operating plan v2',status=BudgetStatus.ACTIVE,activated_at=at,
            notes='Advisory starter allocation. Future contract liabilities remain payable; owners may publish hard limits through a reviewed draft.')
        for category,amount in [('PLAYER_WAGES',1200),('STAFF_WAGES',300),('MARKETPLACE_CAPEX',300),('FACILITY_OPEX',150),('TRAINING_OPEX',150),('TRANSFER_SPEND',400),('FEDERATION_FEES',200)]:
            BudgetLine.objects.create(budget=budget,category=category,planned_amount=Decimal(amount),hard_limit=False)
    return period


def prepare_policies(*, at=None):
    from club_debt.models import CreditPolicy
    from django.db.models import Q
    at=at or timezone.now()
    valid=Q(effective_to__isnull=True)|Q(effective_to__gt=at)
    for model,name,defaults in [(FFPPolicy,'FTG club finance v2',{'max_loss':2700}),(CreditPolicy,'FTG club credit v2',{})]:
        if not model.objects.filter(is_active=True,effective_from__lte=at).filter(valid).exists():
            prior=model.objects.filter(name=name).order_by('-version').first()
            model.objects.get_or_create(name=name,version=prior.version+1 if prior else 2,defaults={'effective_from':at,**defaults})
