"""
Adiciona colunas/tabelas que o Django espera mas o SQLite do Flask não tinha.
Seguro rodar várias vezes (idempotente).
"""
from django.core.management.base import BaseCommand
from django.db import connection


def _column_exists(cursor, table: str, column: str) -> bool:
    cursor.execute(f"PRAGMA table_info([{table}])")
    return column in {row[1] for row in cursor.fetchall()}


def _table_exists(cursor, table: str) -> bool:
    cursor.execute(
        "SELECT name FROM sqlite_master WHERE type='table' AND name=%s",
        [table],
    )
    return cursor.fetchone() is not None


class Command(BaseCommand):
    help = "Sincroniza schema SQLite legado (Flask) com requisitos do Django Auth"

    def handle(self, *args, **options):
        with connection.cursor() as cursor:
            user_columns = [
                ("last_login", "DATETIME NULL"),
                ("is_superuser", "BOOLEAN NOT NULL DEFAULT 0"),
                ("is_active", "BOOLEAN NOT NULL DEFAULT 1"),
                ("is_staff", "BOOLEAN NOT NULL DEFAULT 0"),
            ]
            for col, ddl in user_columns:
                if not _column_exists(cursor, "users", col):
                    cursor.execute(f"ALTER TABLE users ADD COLUMN {col} {ddl}")
                    self.stdout.write(self.style.SUCCESS(f"users.{col} adicionada"))
                else:
                    self.stdout.write(f"users.{col} já existe")

            # Tabelas M2M do PermissionsMixin (se migrate --fake pulou)
            m2m_tables = [
                "accounts_user_groups",
                "accounts_user_user_permissions",
            ]
            for table in m2m_tables:
                if _table_exists(cursor, table):
                    self.stdout.write(f"{table} já existe")
                else:
                    self.stdout.write(
                        self.style.WARNING(
                            f"{table} ausente — rode: python manage.py migrate accounts"
                        )
                    )

        self.stdout.write(self.style.SUCCESS("Schema de usuários sincronizado."))
