import time
from typing import Sequence, Type

import orjson
from tortoise import Model, Tortoise, run_async

from service.config import TORTOISE_ORM
from service.database.models import User


async def do_export():
    export_ts = int(time.time())
    models: Sequence[Type[Model]] = (User,)
    await Tortoise.init(TORTOISE_ORM)
    for filename, model in ((model._meta.db_table, model) for model in models):
        all_objects = await model.all().order_by("id").values()
        if all_objects:
            with open(f"fixtures/{export_ts}__{filename}.json", "wb") as f:
                f.write(orjson.dumps(all_objects))


def main():
    start_ts = time.time()
    run_async(do_export())
    end_ts = time.time()
    print(f"Export completed in {end_ts - start_ts:.3f}s")


if __name__ == "__main__":
    main()
