"""python manage.py import_laravel --storage /chemin/journal/storage/app/public [--dry-run]

Lit la base Laravel (connexion `legacy`, LEGACY_DATABASE_URL) sans jamais y écrire.
"""

from django.core.management.base import BaseCommand, CommandError
from django.db import connections, transaction

from apps.legacy.importer import LaravelImporter


class DryRun(Exception):
    pass


class Command(BaseCommand):
    help = "Importe les données du site Laravel (lecture seule de l'ancienne base)."

    def add_arguments(self, parser):
        parser.add_argument("--storage", help="Dossier storage/app/public du projet Laravel (fichiers à copier).")
        parser.add_argument("--dry-run", action="store_true", help="Simule l'import puis annule tout (aucun fichier copié).")

    def handle(self, *args, **opts):
        if "legacy" not in connections.databases:
            raise CommandError("Définissez LEGACY_DATABASE_URL (base Laravel) dans le fichier .env.")
        storage = None if opts["dry_run"] else opts["storage"]
        with connections["legacy"].cursor() as cursor:
            importer = LaravelImporter(cursor, storage_dir=storage)
            try:
                with transaction.atomic():
                    report = importer.run()
                    if opts["dry_run"]:
                        raise DryRun
            except DryRun:
                report = importer.r
                self.stdout.write(self.style.WARNING("Simulation : toutes les écritures ont été annulées."))

        self.stdout.write(self.style.SUCCESS("Import terminé." if not opts["dry_run"] else "Résultat de la simulation :"))
        for key, n in report.counts.items():
            self.stdout.write(f"  {key:<24} {n}")
        if report.warnings:
            self.stdout.write(self.style.WARNING(f"\n{len(report.warnings)} point(s) à vérifier :"))
            for w in report.warnings:
                self.stdout.write(f"  - {w}")
