import logging

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.promotion.coupon.scheduler")

SCHEDULER_TICK_SECONDS = 3600
BATCH_LIMIT = 200

_scheduler: AsyncIOScheduler | None = None


async def _job_refund_expired_member_coupons() -> None:
    result = await task_center_service.run_task("promotion_coupon_refund_expired", trigger_type="schedule")
    log_task_result(
        log,
        "promotion coupon refund scheduler",
        result,
        activity_keys=("refunded_count", "refunded_points"),
    )


async def _job_notify_expiring_coupons() -> None:
    result = await task_center_service.run_task("promotion_coupon_notify_expiring", trigger_type="schedule")
    log_task_result(
        log,
        "promotion coupon reminder scheduler",
        result,
        activity_keys=("notified",),
    )


def start_promotion_coupon_scheduler() -> None:
    global _scheduler
    if _scheduler is not None:
        return
    scheduler = AsyncIOScheduler(timezone="UTC")
    scheduler.add_job(
        _job_refund_expired_member_coupons,
        trigger=IntervalTrigger(seconds=SCHEDULER_TICK_SECONDS),
        id="promotion_coupon_refund_expired",
        max_instances=1,
        coalesce=True,
        replace_existing=True,
    )
    scheduler.add_job(
        _job_notify_expiring_coupons,
        trigger=IntervalTrigger(seconds=SCHEDULER_TICK_SECONDS),
        id="promotion_coupon_notify_expiring",
        max_instances=1,
        coalesce=True,
        replace_existing=True,
    )
    scheduler.start()
    _scheduler = scheduler
    log.debug("promotion coupon scheduler started: tick=%ss", SCHEDULER_TICK_SECONDS)


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