"""Publish per-call analytics jobs (event-driven after STT)."""

from __future__ import annotations

import json
import logging
import os
from typing import Any, Dict

import pika

logger = logging.getLogger(__name__)


def event_driven_analytics_enabled() -> bool:
    """When true, STT publishes analytics_jobs and orchestrator skips inline batch analytics."""
    return os.getenv("STT_ENQUEUE_ANALYTICS_ALWAYS", "1").lower() not in ("0", "false", "no")


def analytics_queue_name() -> str:
    return os.getenv("RABBITMQ_ANALYTICS_QUEUE", "analytics_jobs")


def publish_analytics_job(bid: str, call_id: str) -> bool:
    """Enqueue analytics for one call. Returns False if publish fails."""
    bid = str(bid).strip()
    call_id = str(call_id).strip()
    if not bid or not call_id:
        return False
    payload: Dict[str, Any] = {"bid": bid, "call_id": call_id}
    host = os.getenv("RABBITMQ_HOST", "localhost")
    port = int(os.getenv("RABBITMQ_PORT", "5672"))
    user = os.getenv("RABBITMQ_USER", "guest")
    password = os.getenv("RABBITMQ_PASSWORD", "guest")
    queue = analytics_queue_name()
    try:
        conn = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=host,
                port=port,
                credentials=pika.PlainCredentials(user, password),
                heartbeat=600,
            )
        )
        channel = conn.channel()
        channel.queue_declare(queue=queue, durable=True)
        channel.basic_publish(
            exchange="",
            routing_key=queue,
            body=json.dumps(payload),
            properties=pika.BasicProperties(delivery_mode=2),
        )
        conn.close()
        logger.info("[%s/%s] Published analytics job to %s", bid, call_id, queue)
        return True
    except Exception as exc:
        logger.warning("[%s/%s] Failed to publish analytics job: %s", bid, call_id, exc)
        return False
