"""Periodic repair worker for comparison records with missing LLM token cost."""
from __future__ import annotations

import asyncio
import contextlib
import logging

from app.core.config import settings
from app.services.comparison_llm_backfill import repair_missing_comparison_llm_costs
from app.services.pricebot_llm_calls import pricebot_llm_auth_ready

logger = logging.getLogger("shagua.llm_cost_backfill_worker")


async def _run_loop() -> None:
    interval = max(60, int(settings.LLM_COST_BACKFILL_INTERVAL_SEC))
    logger.info(
        "LLM cost backfill worker started interval=%ss batch=%s lookback_days=%s",
        interval,
        settings.LLM_COST_BACKFILL_BATCH_SIZE,
        settings.LLM_COST_BACKFILL_LOOKBACK_DAYS,
    )
    try:
        while True:
            try:
                auth_ready = await asyncio.to_thread(pricebot_llm_auth_ready)
                if auth_ready:
                    result = await asyncio.to_thread(
                        repair_missing_comparison_llm_costs,
                        limit=settings.LLM_COST_BACKFILL_BATCH_SIZE,
                        lookback_days=settings.LLM_COST_BACKFILL_LOOKBACK_DAYS,
                    )
                    logger.info("LLM cost backfill batch result=%s", result)
                else:
                    logger.error(
                        "LLM cost backfill skipped: PriceBot internal auth is not ready"
                    )
            except Exception:  # noqa: BLE001
                logger.exception("LLM cost backfill batch failed")
            await asyncio.sleep(interval)
    except asyncio.CancelledError:
        logger.info("LLM cost backfill worker stopped")
        raise


def start_llm_cost_backfill_worker() -> asyncio.Task | None:
    if not settings.LLM_COST_BACKFILL_ENABLED:
        logger.info("LLM cost backfill worker disabled")
        return None
    if not settings.INTERNAL_API_SECRET:
        logger.warning(
            "LLM cost backfill worker not started: INTERNAL_API_SECRET is empty"
        )
        return None
    return asyncio.create_task(_run_loop(), name="llm-cost-backfill")


async def stop_llm_cost_backfill_worker(task: asyncio.Task | None) -> None:
    if task is None:
        return
    task.cancel()
    with contextlib.suppress(asyncio.CancelledError):
        await task
