import os

from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from dotenv import load_dotenv


class Command(BaseCommand):
    help = "Sets up social authentication apps"

    def handle(self, *args, **kwargs):
        # Load environment variables
        load_dotenv()

        # Get environment variables
        google_client_id = os.getenv("GOOGLE_CLIENT_ID")
        google_client_secret = os.getenv("GOOGLE_CLIENT_SECRET")
        discord_client_id = os.getenv("DISCORD_CLIENT_ID")
        discord_client_secret = os.getenv("DISCORD_CLIENT_SECRET")

        # DEBUG: Log environment variable values
        self.stdout.write(
            f"DEBUG: google_client_id type: {type(google_client_id)}, value: {
                google_client_id
            }"
        )
        self.stdout.write(
            f"DEBUG: google_client_secret type: {type(google_client_secret)}, value: {
                google_client_secret
            }"
        )
        self.stdout.write(
            f"DEBUG: discord_client_id type: {type(discord_client_id)}, value: {
                discord_client_id
            }"
        )
        self.stdout.write(
            f"DEBUG: discord_client_secret type: {type(discord_client_secret)}, value: {
                discord_client_secret
            }"
        )

        if not all(
            [
                google_client_id,
                google_client_secret,
                discord_client_id,
                discord_client_secret,
            ]
        ):
            self.stdout.write(self.style.ERROR("Missing required environment variables"))
            self.stdout.write(f"DEBUG: google_client_id is None: {google_client_id is None}")
            self.stdout.write(f"DEBUG: google_client_secret is None: {google_client_secret is None}")
            self.stdout.write(f"DEBUG: discord_client_id is None: {discord_client_id is None}")
            self.stdout.write(f"DEBUG: discord_client_secret is None: {discord_client_secret is None}")
            return

        # Get or create the default site
        site, _ = Site.objects.get_or_create(id=1, defaults={"domain": "localhost:8000", "name": "localhost"})

        # Set up Google
        google_app, created = SocialApp.objects.get_or_create(
            provider="google",
            defaults={
                "name": "Google",
                "client_id": google_client_id,
                "secret": google_client_secret,
            },
        )
        if not created:
            self.stdout.write(
                f"DEBUG: About to assign google_client_id: {google_client_id} (type: {
                    type(google_client_id)
                })"
            )
            if google_client_id is not None and google_client_secret is not None:
                google_app.client_id = google_client_id
                google_app.secret = google_client_secret
                google_app.save()
                self.stdout.write("DEBUG: Successfully updated Google app")
            else:
                self.stdout.write(self.style.ERROR("Google client_id or secret is None, skipping update."))
        google_app.sites.add(site)

        # Set up Discord
        discord_app, created = SocialApp.objects.get_or_create(
            provider="discord",
            defaults={
                "name": "Discord",
                "client_id": discord_client_id,
                "secret": discord_client_secret,
            },
        )
        if not created:
            self.stdout.write(
                f"DEBUG: About to assign discord_client_id: {discord_client_id} (type: {
                    type(discord_client_id)
                })"
            )
            if discord_client_id is not None and discord_client_secret is not None:
                discord_app.client_id = discord_client_id
                discord_app.secret = discord_client_secret
                discord_app.save()
                self.stdout.write("DEBUG: Successfully updated Discord app")
            else:
                self.stdout.write(self.style.ERROR("Discord client_id or secret is None, skipping update."))
        discord_app.sites.add(site)

        self.stdout.write(self.style.SUCCESS("Successfully set up social auth apps"))
