import asyncio

from snek.app import app


async def fix_message(message):
    message = {
        "uid": message["uid"],
        "user_uid": message["user_uid"],
        "text": message["message"],
        "sent": message["created_at"],
    }
    user = await app.services.user.get(uid=message["user_uid"])
    message["user"] = user and user["username"] or None
    return (message["user"] or "") + ": " + (message["text"] or "")


async def dump_public_channels():
    result = []
    for channel in app.db["channel"].find(
        is_private=False, is_listed=True, tag="public"
    ):
        print(f"Dumping channel: {channel['label']}.")
        result += [
            await fix_message(record)
            for record in app.db["channel_message"].find(
                channel_uid=channel["uid"], order_by="created_at"
            )
        ]
        print("Dump succesfull!")
    print("Converting to json.")
    print("Converting succesful, now writing to dump.json")
    with open("dump.txt", "w") as f:
        f.write("\n\n".join(result))
    print("Dump written to dump.json")


if __name__ == "__main__":
    asyncio.run(dump_public_channels())
