# Generated by Django 5.2.12 on 2026-03-26 20:31

from django.db import migrations
from django.db import models

_MODE_MAP = {
    "skip": "auto",
    "redo": "redo",
    "force": "force",
    "skip_noarchive": "auto",
}

_ARCHIVE_MAP = {
    # never skip  -> always generate
    "never": "always",
    # skip when text present -> auto
    "with_text": "auto",
    # always skip -> never generate
    "always": "never",
}


def migrate_old_values(apps, schema_editor):
    ApplicationConfiguration = apps.get_model("paperless", "ApplicationConfiguration")
    for config in ApplicationConfiguration.objects.all():
        old_mode = config.mode
        old_skip = config.skip_archive_file

        # Map the old mode value
        if old_mode in _MODE_MAP:
            config.mode = _MODE_MAP[old_mode]

        # Map skip_archive_file -> archive_file_generation
        if old_skip in _ARCHIVE_MAP:
            config.archive_file_generation = _ARCHIVE_MAP[old_skip]

        # skip_noarchive implied no archive file; set that if the user
        # didn't already have an explicit skip_archive_file preference
        if old_mode == "skip_noarchive" and old_skip is None:
            config.archive_file_generation = "never"

        config.save()


class Migration(migrations.Migration):
    dependencies = [
        ("paperless", "0007_optimize_integer_field_sizes"),
    ]

    operations = [
        # 1. Update mode choices in-place (old values still in the column)
        migrations.AlterField(
            model_name="applicationconfiguration",
            name="mode",
            field=models.CharField(
                blank=True,
                choices=[
                    ("auto", "auto"),
                    ("force", "force"),
                    ("redo", "redo"),
                    ("off", "off"),
                ],
                max_length=16,
                null=True,
                verbose_name="Sets the OCR mode",
            ),
        ),
        # 2. Add the new field
        migrations.AddField(
            model_name="applicationconfiguration",
            name="archive_file_generation",
            field=models.CharField(
                blank=True,
                choices=[("auto", "auto"), ("always", "always"), ("never", "never")],
                max_length=8,
                null=True,
                verbose_name="Controls archive file generation",
            ),
        ),
        # 3. Migrate data from old values to new
        migrations.RunPython(
            migrate_old_values,
            migrations.RunPython.noop,
        ),
        # 4. Drop the old field
        migrations.RemoveField(
            model_name="applicationconfiguration",
            name="skip_archive_file",
        ),
    ]
