from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
from videos.models import Video, Series, Channel
import json


class Command(BaseCommand):
    help = "Find or create a Video by ID and output it as JSON"

    def add_arguments(self, parser):
        parser.add_argument("video_id", type=str, help="The video ID to find or create")

    def handle(self, *args, **options):
        instance = Video.find_or_create(options.get("video_id", ""), overwrite=True)
        data = json.loads(serializers.serialize("json", [instance]))[0]

        # --- Enrich with series model ---
        if instance.tv_series_id:
            series_instance = instance.tv_series
            series_json = json.loads(serializers.serialize("json", [series_instance]))[
                0
            ]
            data["series"] = series_json  # new nested field

        if instance.channel_id:
            channel_instance = instance.channel
            channel_json = json.loads(
                serializers.serialize("json", [channel_instance])
            )[0]
            data["channel"] = channel_json  # new nested field

        self.stdout.write(json.dumps(data, indent=2))
