"""Automation read-only selectors (task 3.8.2)."""

from __future__ import annotations

from django.db.models import QuerySet


def get_rules_for_event(tenant_id: int, event_name: str) -> "QuerySet":
    """Return active event-triggered rules that match *event_name*."""
    from simorgh.apps.automation.models import AutomationRule, TriggerType

    return AutomationRule.objects.filter(
        tenant_id=tenant_id,
        trigger_type=TriggerType.EVENT,
        trigger_event=event_name,
        is_active=True,
    )


def list_rules(tenant_id: int) -> "QuerySet":
    """Return all rules for *tenant_id* ordered by creation date (newest first)."""
    from simorgh.apps.automation.models import AutomationRule

    return AutomationRule.objects.filter(tenant_id=tenant_id).order_by("-created_at")


def get_execution_history(rule_id: int, tenant_id: int) -> "QuerySet":
    """Return executions for *rule_id* within *tenant_id*, newest first."""
    from simorgh.apps.automation.models import AutomationExecution

    return AutomationExecution.objects.filter(
        rule_id=rule_id,
        tenant_id=tenant_id,
    ).order_by("-started_at")
