from decimal import Decimal, ROUND_HALF_UP

from django.db import migrations
from django.utils import timezone


MONEY_QUANTIZER = Decimal('0.01')
DEFAULT_TARGET_MULTIPLIER = Decimal('2.00')
DEFAULT_COMPLETION_DAYS = 35


def quantize_money(value):
    return Decimal(value).quantize(MONEY_QUANTIZER, rounding=ROUND_HALF_UP)


def backfill_signal_plans(apps, schema_editor):
    Deposit = apps.get_model('deposits', 'Deposit')
    SignalProgramSettings = apps.get_model('signals', 'SignalProgramSettings')
    UserSignalPlan = apps.get_model('signals', 'UserSignalPlan')

    settings = SignalProgramSettings.objects.order_by('id').first()
    target_multiplier = DEFAULT_TARGET_MULTIPLIER
    completion_days = DEFAULT_COMPLETION_DAYS

    if settings:
        if settings.target_multiplier and settings.target_multiplier > Decimal('1.00'):
            target_multiplier = Decimal(settings.target_multiplier)
        if settings.completion_days and settings.completion_days > 0:
            completion_days = settings.completion_days

    approved_deposits = Deposit.objects.filter(status='APPROVED', signal_plan__isnull=True)

    for deposit in approved_deposits:
        principal_amount = quantize_money(deposit.amount)
        target_amount = quantize_money(principal_amount * target_multiplier)
        target_profit_amount = quantize_money(target_amount - principal_amount)
        daily_profit_amount = quantize_money(target_profit_amount / Decimal(completion_days))

        UserSignalPlan.objects.create(
            user_id=deposit.user_id,
            deposit_id=deposit.id,
            principal_amount=principal_amount,
            target_multiplier=target_multiplier,
            target_amount=target_amount,
            target_profit_amount=target_profit_amount,
            credited_profit_amount=Decimal('0.00'),
            daily_profit_amount=daily_profit_amount,
            completion_days=completion_days,
            accepted_days=0,
            status='ACTIVE',
            started_at=deposit.verified_at or deposit.updated_at or deposit.created_at or timezone.now(),
        )


def reverse_backfill_signal_plans(apps, schema_editor):
    UserSignalPlan = apps.get_model('signals', 'UserSignalPlan')
    UserSignalPlan.objects.filter(
        deposit__status='APPROVED',
        accepted_days=0,
        credited_profit_amount=Decimal('0.00'),
        daily_signals__isnull=True,
    ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('signals', '0002_signalprogramsettings_usersignalplan_and_more'),
    ]

    operations = [
        migrations.RunPython(backfill_signal_plans, reverse_backfill_signal_plans),
    ]
