"""
Renseigne la date de normalisation des factures deja emises.

La DGI classe une facture a la date/heure de sa normalisation (dateTime de
l'e-MCF, DT du MCF), conservee en texte dans `dateTimedgi`. Les rapports
utilisent desormais cette date : une vente creee a 23:59:59 et normalisee
apres minuit compte, comme a la DGI, le lendemain (ou le mois suivant).
"""

from datetime import datetime

from django.db import migrations
from django.utils import timezone


FORMATS = ("%d/%m/%Y %H:%M:%S", "%Y%m%d%H%M%S", "%d/%m/%Y %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S")


def _parse(text):
    text = str(text or "").strip()
    for fmt in FORMATS:
        try:
            return timezone.make_aware(datetime.strptime(text, fmt))
        except ValueError:
            continue
    return None


def backfill(apps, schema_editor):
    Commande = apps.get_model("facturation", "Commande")
    alias = schema_editor.connection.alias
    batch = []
    queryset = (
        Commande.objects.using(alias)
        .filter(date_fiscale__isnull=True)
        .exclude(dateTimedgi__isnull=True)
        .exclude(dateTimedgi="")
        .only("pk", "dateTimedgi")
    )
    for commande in queryset.iterator(chunk_size=2000):
        parsed = _parse(commande.dateTimedgi)
        if parsed is None:
            continue
        commande.date_fiscale = parsed
        batch.append(commande)
        if len(batch) >= 1000:
            Commande.objects.using(alias).bulk_update(batch, ["date_fiscale"])
            batch = []
    if batch:
        Commande.objects.using(alias).bulk_update(batch, ["date_fiscale"])


class Migration(migrations.Migration):

    dependencies = [
        ("facturation", "0063_commande_montants_fiscaux_dgi"),
    ]

    operations = [
        migrations.RunPython(backfill, migrations.RunPython.noop),
    ]
