from faststream import Context
from cattle_grid.database.activity_pub_actor import StoredActivity

from uuid6 import uuid7
from datetime import datetime

from cattle_grid.model.processing import StoreActivityMessage
from cattle_grid.dependencies.globals import global_container
from cattle_grid.dependencies.processing import MessageActor
from cattle_grid.dependencies import CommittingSession


async def store_activity_subscriber(
    message: StoreActivityMessage,
    actor: MessageActor,
    session: CommittingSession,
    broker=Context(),
):
    """This method used internally to store activities
    generated by `cattle_grid`, e.g. an automatically generated
    accept requests. We note that it assigns an id to
    the activity.

    After storing the activity, it is published to the
    appropriate `outgoing.*` topic, which triggers sending
    the activity.
    """
    base_url = "/".join(actor.actor_id.split("/")[:-2])
    uuid = str(uuid7())
    activity_id = f"{base_url}/object/{uuid}"

    activity = message.data
    activity["id"] = activity_id
    activity_type = activity.get("type")

    session.add(
        StoredActivity(id=uuid, actor=actor, data=activity, published=datetime.now())
    )

    await broker.publish(
        {"actor": actor.actor_id, "data": activity},
        routing_key=f"outgoing.{activity_type}",
        exchange=global_container.internal_exchange,
    )
