import socket

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connection
from django.db.migrations.executor import MigrationExecutor


class Command(BaseCommand):
    help = "Diagnostica o arranque local, a base de dados e as contas administrativas."

    def add_arguments(self, parser):
        parser.add_argument("--port", type=int, default=8000)

    def handle(self, *args, **options):
        port = options["port"]
        self.stdout.write(self.style.MIGRATE_HEADING("Diagnóstico local Kreate4Web"))
        self.stdout.write(f"DEBUG: {settings.DEBUG}")
        self.stdout.write(f"Base de dados: {settings.DATABASES['default']['ENGINE']}")
        self.stdout.write(f"SECURE_SSL_REDIRECT: {settings.SECURE_SSL_REDIRECT}")

        try:
            connection.ensure_connection()
            self.stdout.write(self.style.SUCCESS("Base de dados: ligação concluída"))
        except Exception as exc:
            self.stdout.write(self.style.ERROR(f"Base de dados: erro — {exc}"))
            return

        executor = MigrationExecutor(connection)
        pending = executor.migration_plan(executor.loader.graph.leaf_nodes())
        if pending:
            self.stdout.write(self.style.WARNING(f"Migrações pendentes: {len(pending)}"))
            self.stdout.write("Execute: python manage.py migrate")
        else:
            self.stdout.write(self.style.SUCCESS("Migrações: atualizadas"))

        User = get_user_model()
        superusers = list(User.objects.filter(is_superuser=True, is_active=True).values_list("username", flat=True))
        if superusers:
            self.stdout.write(self.style.SUCCESS("Superutilizadores ativos: " + ", ".join(superusers)))
        else:
            self.stdout.write(self.style.WARNING("Não existe superutilizador ativo."))
            self.stdout.write("Execute: python manage.py createsuperuser")

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            in_use = sock.connect_ex(("127.0.0.1", port)) == 0
        finally:
            sock.close()
        if in_use:
            self.stdout.write(self.style.WARNING(f"A porta {port} já está a ser utilizada."))
            self.stdout.write(f"Experimente: python manage.py runserver 127.0.0.1:{port + 1}")
        else:
            self.stdout.write(self.style.SUCCESS(f"Porta {port}: disponível"))

        self.stdout.write("")
        self.stdout.write("Arranque recomendado:")
        self.stdout.write("  python manage.py runserver 127.0.0.1:8000")
        self.stdout.write("  Login único: http://127.0.0.1:8000/")
        self.stdout.write("  Backoffice:  http://127.0.0.1:8000/admin/")
        self.stdout.write("  Cliente:     http://127.0.0.1:8000/portal/")
