import logging
from datetime import datetime, timedelta, timezone

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger

from app.services.scheduler_log import log_task_result
from app.services import task_center_service

log = logging.getLogger("qycw.instance.lifecycle.scheduler")

CHECK_INTERVAL_MINUTES = 30
INITIAL_DELAY_SECONDS = 45

_scheduler: AsyncIOScheduler | None = None


async def _job_process_expired_instances() -> None:
    result = await task_center_service.run_task("instance_lifecycle", trigger_type="schedule")
    log_task_result(
        log,
        "instance lifecycle scheduler",
        result,
        activity_keys=(
            "auto_renew.renewed",
            "auto_renew.insufficient",
            "auto_renew.blocked",
            "auto_renew.failed",
            "reminders.sent",
            "reminders.failed",
            "expired.suspended",
            "expired.deleted",
            "expired.failed",
        ),
    )


def start_instance_lifecycle_scheduler() -> None:
    global _scheduler
    if _scheduler is not None:
        return
    scheduler = AsyncIOScheduler(timezone="UTC")
    first_run = datetime.now(timezone.utc) + timedelta(seconds=INITIAL_DELAY_SECONDS)
    scheduler.add_job(
        _job_process_expired_instances,
        IntervalTrigger(minutes=CHECK_INTERVAL_MINUTES, jitter=60, start_date=first_run),
        id="instance_lifecycle",
        next_run_time=first_run,
        max_instances=1,
        coalesce=True,
        misfire_grace_time=600,
    )
    scheduler.start()
    _scheduler = scheduler
    log.debug("instance lifecycle scheduler started: interval=%dm", CHECK_INTERVAL_MINUTES)


def shutdown_instance_lifecycle_scheduler() -> None:
    global _scheduler
    if _scheduler is None:
        return
    _scheduler.shutdown(wait=False)
    _scheduler = None
