from typing import Any

from celery import Task
from sqlalchemy.orm import Session

from .service import TaskTrackerService


def track_and_dispatch(
    *,
    db: Session,
    task: Task,
    tenant_id: int,
    task_name: str,
    task_group: str,
    company_id: int | None = None,
    requested_by_user: str | None = None,
    task_origin: str | None = None,
    args: list[Any] | None = None,
    kwargs: dict[str, Any] | None = None,
    task_id: str | None = None,
    meta_payload: dict[str, Any] | None = None,
):
    celery_task = task.apply_async(args=args or [], kwargs=kwargs or {}, task_id=task_id)
    tracker = TaskTrackerService(db)
    tracker.register_dispatch(
        task_id=celery_task.id,
        tenant_id=tenant_id,
        company_id=company_id,
        requested_by_user=requested_by_user,
        task_name=task_name,
        task_group=task_group,
        task_origin=task_origin,
        meta_payload=meta_payload,
    )
    return celery_task
