# Generated by Django 5.0.6 on 2024-07-24 20:53

import logging
import django.db.models.deletion
from django.db import migrations, models
from app.providers import tmdb
from django.conf import settings
logger = logging.getLogger(__name__)


def forward_func(apps, _):
    item_model = apps.get_model('app', 'Item')
    for model_name in ['TV', 'Season', 'Manga', 'Anime', 'Movie', 'Game', 'Episode']:
        logger.info(f"Starting migration for {model_name.lower()}s.")
        model = apps.get_model('app', model_name)
        instances = []
        for instance in model.objects.all():

            season_number = None
            episode_number = None
            if model_name == 'Season':
                season_number = instance.season_number
            elif model_name == 'Episode':
                season_number = instance.related_season.season_number
                episode_number = instance.episode_number
                instance.media_id = instance.related_season.media_id
                instance.title = instance.related_season.title
                instance.image = episode_img(instance)
                
            item, _ = item_model.objects.get_or_create(
                media_id=instance.media_id,
                media_type=model_name.lower(),
                season_number=season_number,
                episode_number=episode_number,
                defaults={
                    "title": instance.title,
                    "image": instance.image,
                }
            )
            instance.item = item
            instances.append(instance)
        model.objects.bulk_update(instances, ['item'])

        logger.info(f"Finished migration for {model_name.lower()}s.")


def reverse_func(apps, _):
    for model_name in ['TV', 'Season', 'Manga', 'Anime', 'Movie', 'Game', 'Episode']:
        model = apps.get_model('app', model_name)
        model.objects.update(item=None)


def episode_img(instance):
    season_metadata = tmdb.season(instance.related_season.media_id, instance.related_season.season_number)
    
    for episode in season_metadata["episodes"]:
        if episode["episode_number"] == instance.episode_number and episode["still_path"]:
            return f"http://image.tmdb.org/t/p/original{episode['still_path']}"
    return settings.IMG_NONE


class Migration(migrations.Migration):

    dependencies = [
        ('app', '0018_item'),
    ]

    operations = [
        migrations.AddField(
            model_name='anime',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='episode',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='game',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='manga',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='movie',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='season',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.AddField(
            model_name='tv',
            name='item',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app.item'),
        ),
        migrations.RunPython(forward_func, reverse_func),

    ]
