# Generated migration for initial fiscal period
from django.db import migrations
from datetime import date
from dateutil.relativedelta import relativedelta


def create_initial_fiscal_period(apps, schema_editor):
    """
    Create initial fiscal period for the current month if none exists.
    
    This ensures the accounting system has at least one open period
    for recording transactions.
    """
    FiscalPeriod = apps.get_model('accounting', 'FiscalPeriod')
    
    # Check if any fiscal periods exist
    if FiscalPeriod.objects.exists():
        # Fiscal periods already exist, skip creation
        return
    
    # Calculate current month start and end dates
    today = date.today()
    month_start = date(today.year, today.month, 1)
    
    # Calculate last day of current month
    if today.month == 12:
        month_end = date(today.year, 12, 31)
    else:
        next_month_start = date(today.year, today.month + 1, 1)
        month_end = next_month_start - relativedelta(days=1)
    
    # Generate period name (e.g., "January 2024")
    period_name = month_start.strftime("%B %Y")
    
    # Create the fiscal period
    FiscalPeriod.objects.create(
        name=period_name,
        period_type='monthly',
        start_date=month_start,
        end_date=month_end,
        status='open',
        opening_balances={},
        closing_balances={},
    )


def reverse_initial_fiscal_period(apps, schema_editor):
    """
    Remove the initial fiscal period created by this migration.
    
    Note: This only removes periods created by this migration.
    """
    FiscalPeriod = apps.get_model('accounting', 'FiscalPeriod')
    
    # Calculate current month to identify the period created
    today = date.today()
    month_start = date(today.year, today.month, 1)
    period_name = month_start.strftime("%B %Y")
    
    # Delete only the period that matches the current month
    FiscalPeriod.objects.filter(
        name=period_name,
        period_type='monthly'
    ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0002_initial_accounts'),
    ]

    operations = [
        migrations.RunPython(create_initial_fiscal_period, reverse_initial_fiscal_period),
    ]
