"""
Exporte la base locale dans un fichier SQL aux noms de tables de la production.

Le MySQL de Windows enregistre les noms de tables en minuscules
(`g_erreur_action`) ; le serveur Linux de production distingue les majuscules
et attend `G_Erreur_action`. Une sauvegarde locale ordinaire, importee en
production, creerait donc des tables que FacControl ne retrouverait pas.

Cette commande lance `mysqldump`, puis remet dans le fichier le nom exact
attendu par chaque modele Django (G_Affectation_…, G_Erreur_…, G_Scan_…,
G_taux_…). Elle ne modifie rien dans la base locale.

    python manage.py exporter_base_production
    python manage.py exporter_base_production --sortie D:\\sauvegardes\\base.sql
    python manage.py exporter_base_production --structure-seule

Le fichier contient toutes les donnees de l'entreprise : il est ecrit par
defaut dans le dossier `sauvegardes/`, exclu de git.
"""

import os
import re
import shutil
import subprocess
import tempfile
from pathlib import Path

from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.utils import timezone

MYSQLDUMP_LOCATIONS = (
    r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqldump.exe",
    r"C:\Program Files\MySQL\MySQL Server 8.4\bin\mysqldump.exe",
    r"C:\Program Files\MariaDB\bin\mysqldump.exe",
    r"C:\xampp\mysql\bin\mysqldump.exe",
    r"C:\wamp64\bin\mysql\bin\mysqldump.exe",
)
# Seules les instructions de structure citent un nom de table : les donnees ne sont jamais reecrites.
STRUCTURE_PREFIXES = (
    b"DROP TABLE", b"CREATE TABLE", b"LOCK TABLES", b"ALTER TABLE", b"/*!40000 ALTER TABLE",
    b"-- Table structure", b"-- Dumping data", b"DROP VIEW", b"/*!50001",
)
INSERT_PREFIX = b"INSERT INTO "
INSERT_HEADER_BYTES = 400


def production_table_names():
    """Nom local (minuscules) -> nom attendu par les modeles, pour ceux qui different."""

    mapping = {}
    for model in apps.get_models(include_auto_created=True):
        table = model._meta.db_table
        if table != table.lower():
            mapping[table.lower()] = table
    return mapping


def build_rewriter(mapping):
    """Fonction qui remet les noms de production dans une ligne du fichier SQL."""

    if not mapping:
        return lambda line: line
    encoded = {old.encode(): new.encode() for old, new in mapping.items()}
    pattern = re.compile(b"`(" + b"|".join(re.escape(name) for name in sorted(encoded, key=len, reverse=True)) + b")`")

    def replace(chunk):
        return pattern.sub(lambda match: b"`" + encoded[match.group(1)] + b"`", chunk)

    def rewrite(line):
        stripped = line.lstrip()
        if stripped.startswith(INSERT_PREFIX):
            # Seul l'en-tete « INSERT INTO `table` » est touche, jamais les valeurs.
            head, tail = line[:INSERT_HEADER_BYTES], line[INSERT_HEADER_BYTES:]
            marker = head.find(b" VALUES")
            if marker != -1:
                head, tail = head[:marker], head[marker:] + tail
            return replace(head) + tail
        if stripped.startswith(STRUCTURE_PREFIXES) or b" REFERENCES `" in line[:600]:
            return replace(line)
        return line

    return rewrite


class Command(BaseCommand):
    help = "Exporte la base locale en SQL avec les noms de tables de la production (majuscules conservees)."

    def add_arguments(self, parser):
        parser.add_argument("--sortie", help="Chemin du fichier SQL a ecrire.")
        parser.add_argument("--structure-seule", action="store_true", help="Exporte les tables sans leurs donnees.")
        parser.add_argument("--mysqldump", help="Chemin de mysqldump s'il n'est pas trouve automatiquement.")

    def _find_mysqldump(self, explicit):
        candidates = [explicit] if explicit else []
        candidates.append(shutil.which("mysqldump"))
        candidates.extend(MYSQLDUMP_LOCATIONS)
        for candidate in candidates:
            if candidate and Path(candidate).is_file():
                return str(candidate)
        raise CommandError("mysqldump est introuvable : indiquez son chemin avec --mysqldump.")

    def handle(self, *args, **options):
        database = settings.DATABASES["default"]
        if "mysql" not in database.get("ENGINE", ""):
            raise CommandError("Cette commande ne concerne que les bases MySQL / MariaDB.")

        mapping = production_table_names()
        local_tables = set(connection.introspection.table_names())
        missing = sorted(name for name in mapping if name not in {table.lower() for table in local_tables})
        if missing:
            self.stdout.write(self.style.WARNING("Tables absentes de la base locale : " + ", ".join(missing)))

        if options["sortie"]:
            output = Path(options["sortie"])
        else:
            stamp = timezone.localtime().strftime("%Y%m%d_%H%M")
            suffix = "_structure" if options["structure_seule"] else ""
            output = Path(settings.BASE_DIR) / "sauvegardes" / f"{database['NAME']}_production{suffix}_{stamp}.sql"
        output.parent.mkdir(parents=True, exist_ok=True)

        # Le mot de passe passe par un fichier temporaire, jamais par la ligne de commande.
        credentials = tempfile.NamedTemporaryFile("w", suffix=".cnf", delete=False, encoding="utf-8")
        try:
            credentials.write("[client]\n")
            credentials.write(f"user={database.get('USER', '')}\n")
            credentials.write(f"password=\"{database.get('PASSWORD', '')}\"\n")
            credentials.write(f"host={database.get('HOST') or 'localhost'}\n")
            if database.get("PORT"):
                credentials.write(f"port={database['PORT']}\n")
            credentials.close()

            command = [
                self._find_mysqldump(options["mysqldump"]),
                f"--defaults-extra-file={credentials.name}",
                "--single-transaction", "--quick", "--hex-blob", "--no-tablespaces",
                "--default-character-set=utf8mb4", "--skip-comments=FALSE",
            ]
            if options["structure_seule"]:
                command.append("--no-data")
            command.append(database["NAME"])

            rewrite = build_rewriter(mapping)
            renamed = set()
            created = []
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            with open(output, "wb") as target:
                target.write(
                    b"-- Export FacControl aux noms de tables de la production (majuscules conservees).\n"
                    b"-- Genere par : python manage.py exporter_base_production\n\n"
                )
                for line in process.stdout:
                    new_line = rewrite(line)
                    if new_line.startswith(b"CREATE TABLE `"):
                        name = new_line.split(b"`")[1].decode()
                        created.append(name)
                        if new_line != line:
                            renamed.add(name)
                    target.write(new_line)
            errors = process.stderr.read().decode("utf-8", "replace").strip()
            if process.wait() != 0:
                output.unlink(missing_ok=True)
                raise CommandError(f"mysqldump a echoue : {errors}")
        finally:
            try:
                os.unlink(credentials.name)
            except OSError:
                pass

        expected = set(mapping.values())
        not_renamed = sorted(expected - renamed - {mapping[name] for name in missing})
        lowercase_left = sorted(name for name in created if name in mapping)
        if not_renamed or lowercase_left:
            raise CommandError(
                "Export incomplet : tables non remises au nom de production : "
                + ", ".join(not_renamed + lowercase_left)
            )

        size = output.stat().st_size / (1024 * 1024)
        self.stdout.write(f"{len(created)} tables exportees, dont {len(renamed)} remises au nom de production :")
        for name in sorted(renamed):
            self.stdout.write(f"  {name}")
        self.stdout.write(self.style.SUCCESS(f"Fichier : {output} ({size:.1f} Mo)"))
