"""Celery task: еженедельная синхронизация OSM источников шума для site-finder."""

import logging

from sqlalchemy import text

from app.workers.celery_app import celery_app

logger = logging.getLogger(__name__)


def _log_breadcrumb(level: str, message: str) -> None:
    """Записать строку в nspd_geo_log (job_id=NULL, stage='noise_sync')."""
    try:
        from app.core.db import SessionLocal

        db = SessionLocal()
        try:
            db.execute(
                text(
                    "INSERT INTO nspd_geo_log (job_id, level, stage, message) "
                    "VALUES (NULL, :lvl, 'noise_sync', :msg)"
                ),
                {"lvl": level, "msg": message[:500]},
            )
            db.commit()
        finally:
            db.close()
    except Exception as e:
        logger.warning("noise_sync breadcrumb failed: %s", e)


@celery_app.task(name="tasks.noise_sync.sync_osm_noise_sources_ekb", queue="celery")
def sync_osm_noise_sources_ekb() -> dict:
    """Еженедельная синхронизация OSM шумовых источников из Overpass в osm_noise_sources_ekb.

    Запускается через beat (понедельник 03:30 МСК — через 30 мин после poi-sync).
    Persistent breadcrumbs в nspd_geo_log для диагностики без SSH.
    """
    _log_breadcrumb("info", "task started")
    try:
        from app.services.site_finder.noise_loader import sync_noise_sources_to_db

        result = sync_noise_sources_to_db()
        logger.info("noise_sync done: %s", result)
        _log_breadcrumb("info", f"done: {result}")
        return result
    except Exception as e:
        logger.exception("noise_sync failed: %s", e)
        _log_breadcrumb("error", f"{type(e).__name__}: {e}")
        raise
