from django.core.management.base import BaseCommand
from django.db import connections

from shop_management.models.data.organization import CompanySetting


class Command(BaseCommand):
    help = "Read-only inspection of the application's active database Unicode connection and profile columns."

    def add_arguments(self, parser):
        parser.add_argument("--database", default="default")

    def handle(self, *args, **options):
        connection = connections[options["database"]]
        self.stdout.write(f"Engine: {connection.settings_dict['ENGINE']}")
        self.stdout.write(f"Vendor: {connection.vendor}")
        self.stdout.write(f"Configured charset: {connection.settings_dict.get('OPTIONS', {}).get('charset', '(driver default)')}")
        sample = "پښتو دری ژبه ښ ړ ږ څ ځ ټ ډ ڼ ی ې"
        with connection.cursor() as cursor:
            if connection.vendor == "mysql":
                cursor.execute("SELECT @@character_set_client, @@character_set_connection, @@character_set_results, @@collation_connection")
                values = cursor.fetchone()
                for name, value in zip(("character_set_client", "character_set_connection", "character_set_results", "collation_connection"), values):
                    self.stdout.write(f"Session {name}: {value}")
                cursor.execute(
                    "SELECT COLUMN_NAME, CHARACTER_SET_NAME, COLLATION_NAME "
                    "FROM information_schema.COLUMNS "
                    "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s "
                    "AND CHARACTER_SET_NAME IS NOT NULL ORDER BY ORDINAL_POSITION",
                    [CompanySetting._meta.db_table],
                )
                for name, charset, collation in cursor.fetchall():
                    self.stdout.write(f"Column {name}: {charset} / {collation}")
                # ASCII hex result separates server-side bytes from result decoding.
                cursor.execute("SELECT %s, HEX(%s)", [sample, sample])
                returned, server_hex = cursor.fetchone()
                self.stdout.write(f"Server received exact UTF-8 bytes: {str(server_hex).lower() == sample.encode('utf-8').hex()}")
            else:
                cursor.execute("SELECT %s", [sample])
                returned = cursor.fetchone()[0]
            self.stdout.write(f"Connection Unicode round trip: {'PASS' if returned == sample else 'FAIL'}")
        self.stdout.write("Read-only check complete. No company data was changed. This does not test stored column writes.")
