"""Reporting Engine — event definitions and subscriptions."""

from __future__ import annotations

from simorgh.apps.events.bus import register_event, subscribe

REPORT_EXECUTED = register_event(
    "reporting.report_executed",
    description="Emitted when a report execution completes successfully.",
    payload_keys={
        "execution_id",
        "report_code",
        "report_name",
        "tenant_id",
        "row_count",
        "format",
        "triggered_by",
    },
)

REPORT_SCHEDULED = register_event(
    "reporting.report_scheduled",
    description="Emitted when a scheduled report is created or updated.",
    payload_keys={
        "schedule_id",
        "report_code",
        "cron_expression",
        "tenant_id",
    },
)


@subscribe("reporting.report_executed")
def _on_report_executed_notify(payload: dict) -> None:
    """When a scheduled report executes, notify the schedule's recipients."""

    execution_id = payload.get("execution_id")
    if not execution_id:
        return

    from simorgh.apps.reporting.models import ReportExecution

    try:
        execution = ReportExecution.objects.select_related("schedule").get(pk=execution_id)
    except ReportExecution.DoesNotExist:
        return

    if not execution.schedule:
        return

    # Future: dispatch notifications to schedule.recipients
    # For now this is a placeholder for Notification Engine integration.
