"""
Django management command to fetch Steam Workshop collections
"""

from django.core.management.base import BaseCommand, CommandError
from submissions.utils import create_or_update_collection
from submissions.models import SteamAPIKey, SteamCollection


class Command(BaseCommand):
    help = "Fetch Steam Workshop collection data and save to database"

    def add_arguments(self, parser):
        parser.add_argument("url", type=str, help="Steam Workshop collection URL")
        parser.add_argument(
            "--force",
            action="store_true",
            help="Force refetch even if collection already exists",
        )

    def handle(self, *args, **options):
        url = options["url"]
        force = options["force"]

        self.stdout.write(f"Fetching Steam collection from: {url}")

        api_key = SteamAPIKey.objects.filter(is_active=True).first()

        if not api_key:
            self.stderr.write("No API key defined! Aborting...")
            return

        self.stdout.write(f"Using api key: {api_key}")

        try:
            # Check if collection already exists
            from submissions.utils import SteamCollectionFetcher

            fetcher = SteamCollectionFetcher(api_key.api_key)
            collection_id = fetcher.extract_collection_id(url)

            if collection_id and not force:
                existing = SteamCollection.objects.filter(
                    steam_id=collection_id
                ).first()
                if existing:
                    self.stdout.write(
                        self.style.WARNING(
                            f"Collection {collection_id} already exists (ID: {existing.id}). "
                            "Use --force to refetch."
                        )
                    )
                    return

            # Fetch and create/update collection
            collection, created = create_or_update_collection(url)

            if created:
                self.stdout.write(
                    self.style.SUCCESS(
                        f"Successfully created collection: {collection.title} (ID: {collection.id})"
                    )
                )
            else:
                self.stdout.write(
                    self.style.SUCCESS(
                        f"Successfully updated collection: {collection.title} (ID: {collection.id})"
                    )
                )

            # Display collection info
            self.stdout.write("\nCollection Details:")
            self.stdout.write(f"  Steam ID: {collection.steam_id}")
            self.stdout.write(f"  Title: {collection.title}")
            self.stdout.write(f"  Author: {collection.author_name or 'Unknown'}")
            self.stdout.write(
                f"  Description: {collection.description[:100]}{'...' if len(collection.description) > 100 else ''}"
            )
            self.stdout.write(f"  Total Items: {collection.total_items}")
            self.stdout.write(f"  Unique Visitors: {collection.unique_visitors}")
            self.stdout.write(f"  Current Favorites: {collection.current_favorites}")
            self.stdout.write(f"  Total Favorites: {collection.total_favorites}")

            if collection.items.exists():
                self.stdout.write(f"\nCollection Items ({collection.items.count()}):")
                for item in collection.items.all()[:10]:  # Show first 10 items
                    self.stdout.write(
                        f"  - {item.title} (Steam ID: {item.steam_item_id})"
                    )

                if collection.items.count() > 10:
                    self.stdout.write(
                        f"  ... and {collection.items.count() - 10} more items"
                    )
            else:
                self.stdout.write("\nNo items found in collection.")

        except Exception as e:
            raise CommandError(f"Failed to fetch collection: {e}")
