# Generated by Django 4.2.9 on 2024-01-22 07:56

from pathlib import Path
from typing import Union

from django.db import migrations


def all_subdirectories(path: Union[str, Path]) -> set[str]:
    """Get all subdirectories of the given relative path.

    The "." is excluded.
    """
    return {f"{path}/" for path in set(Path(path).parents) - {Path(".")}}


def add_directories(apps, schema_editor):
    """Add missing directory entries to the database.

    This method is safe to run multiple times.
    """
    ReferencedPath = apps.get_model("storage", "ReferencedPath")
    StorageLocation = apps.get_model("storage", "StorageLocation")
    for storage_location in StorageLocation.all_objects.filter(status="OK").iterator():
        referenced_paths = storage_location.files.values_list("path", flat=True)
        existing_directories = {path for path in referenced_paths if path.endswith("/")}
        all_directories: set[str] = set()
        for path in referenced_paths:
            all_directories.update(all_subdirectories(path))
        if missing_directories := all_directories - existing_directories:
            created_directories = ReferencedPath.objects.bulk_create(
                ReferencedPath(path=path, size=0) for path in missing_directories
            )
            storage_location.files.add(*created_directories)


class Migration(migrations.Migration):
    dependencies = [
        ("storage", "0001_squashed_0009_referencedpath_chunk_size"),
    ]

    operations = [
        migrations.RunPython(add_directories),
    ]
