"""Cron scheduler — reads CronJob rows and enqueues ARQ jobs."""

from __future__ import annotations

import logging
from datetime import UTC, datetime
from typing import Any

import croniter
from sqlalchemy import select

from app.core.db import get_session_factory

logger = logging.getLogger(__name__)


def calculate_next_run(cron_expression: str, from_time: datetime | None = None) -> datetime:
    """Calculate the next run time from a cron expression using croniter."""
    base = from_time or datetime.now(UTC)
    cron = croniter.croniter(cron_expression, base)
    next_dt = cron.get_next(datetime)
    return next_dt


async def scheduler_tick(ctx: dict[str, Any]) -> None:
    """Run every 60s via ARQ cron. Reads active CronJob rows where next_run_at <= now,
    enqueues appropriate ARQ job, updates last_run_at and calculates next_run_at."""
    from app.plugins.builtins.automation.models import AutomationCronJob as CronJob

    now = datetime.now(UTC)
    factory = get_session_factory()

    async with factory() as db:
        result = await db.execute(
            select(CronJob).where(
                CronJob.is_active.is_(True),
                CronJob.next_run_at <= now,
            )
        )
        jobs = list(result.scalars().all())

    if not jobs:
        logger.debug("scheduler_tick: no cron jobs due")
        return

    logger.info("scheduler_tick: %d cron job(s) due", len(jobs))

    for job in jobs:
        try:
            if job.job_type == "agent":
                from app.core.jobs import enqueue_job
                await enqueue_job("run_agent", job.target_id, trigger_type="scheduled")
            elif job.job_type == "automation":
                from app.core.jobs import enqueue_job
                await enqueue_job("run_automation", job.target_id, trigger_type="scheduled")
            else:
                logger.warning("Unknown cron job_type: %s", job.job_type)
                continue

            # Update last_run_at and calculate next_run_at
            async with factory() as db:
                result = await db.execute(select(CronJob).where(CronJob.id == job.id))
                db_job = result.scalar_one_or_none()
                if db_job is None:
                    continue
                db_job.last_run_at = now
                db_job.next_run_at = calculate_next_run(db_job.cron_expression, now)
                await db.flush()

            logger.info("Enqueued %s %s (id=%s)", job.job_type, job.target_id, job.id)

        except Exception:
            logger.exception("Failed to process cron job %s", job.id)
