"""Scheduler monitoring utilities"""

import json
import logging
from datetime import datetime
from typing import Optional

from ..api.progress import get_redis

log = logging.getLogger(__name__)


async def record_job_run(
    account_id: str,
    job_id: str,
    status: str,
    rows: int,
    duration_ms: int,
    error: Optional[str] = None,
) -> None:
    """Record a job execution summary to Redis for monitoring dashboards."""
    try:
        redis = await get_redis()
        if not redis:
            return

        entry = {
            "account_id": account_id,
            "job_id": job_id,
            "status": status,
            "rows": rows,
            "duration_ms": duration_ms,
            "error": error,
            "recorded_at": datetime.utcnow().isoformat(),
        }

        key = f"scheduler:metrics:{account_id}"
        await redis.lpush(key, json.dumps(entry))
        await redis.ltrim(key, 0, 199)  # keep latest 200 entries per account
        await redis.expire(key, 60 * 60 * 24 * 7)  # 7 days retention

        # Global stream for analytics
        await redis.lpush("scheduler:metrics:global", json.dumps(entry))
        await redis.ltrim("scheduler:metrics:global", 0, 999)
        await redis.expire("scheduler:metrics:global", 60 * 60 * 24 * 7)

    except Exception as exc:
        log.error("Failed to record scheduler metric: %s", exc)
