# Generated by Django 5.0.12 on 2025-11-28 13:11

from django.db import migrations, models

def handle_data(apps, schema_editor):
    PortfolioPortfolioThroughModel = apps.get_model('wbportfolio', 'PortfolioPortfolioThroughModel')
    PortfolioPortfolioThroughModel.objects.filter(type="PRIMARY").update(type="LOOK_THROUGH")
    from wbportfolio.models.portfolio import Portfolio
    for portfolio in Portfolio.objects.all():
        if portfolio.assets.exists():
            val_date = portfolio.assets.latest("date").date
            for parent_ptf, _ in portfolio.get_parent_portfolios(val_date):
                PortfolioPortfolioThroughModel.objects.get_or_create(portfolio_id=portfolio.id, dependency_portfolio_id=parent_ptf.id, defaults={"type": "HIERARCHICAL"})
class Migration(migrations.Migration):

    dependencies = [
        ('wbportfolio', '0092_order_quantization_error_alter_orderproposal_status'),
    ]

    operations = [
        migrations.RemoveConstraint(
            model_name='portfolioportfoliothroughmodel',
            name='unique_primary',
        ),
        migrations.AlterField(
            model_name='portfolioportfoliothroughmodel',
            name='type',
            field=models.CharField(choices=[('LOOK_THROUGH', 'Look-through'), ('MODEL', 'Model'), ('CUSTODIAN', 'Custodian'), ('HIERARCHICAL', 'Hierarchical')], default='LOOK_THROUGH', verbose_name='Type'),
        ),
        migrations.AddConstraint(
            model_name='portfolioportfoliothroughmodel',
            constraint=models.UniqueConstraint(condition=models.Q(('type', 'LOOK_THROUGH')), fields=('portfolio', 'type'), name='unique_lookthrough'),
        ),
        migrations.RunPython(handle_data)
    ]
