"""
AnyDesk local sessions sync job.
Polls local AnyDesk bridge endpoint and enriches local session rows.
"""

import logging

from app.core.config import settings
from app.services.anydesk import AnyDeskService

logger = logging.getLogger(__name__)
anydesk_service = AnyDeskService()


async def sync_anydesk_local_sessions():
    """Sync AnyDesk sessions from local endpoint every N minutes."""
    if not settings.ANYDESK_LOCAL_SYNC_ENABLED:
        return

    try:
        logger.info("🔄 AnyDesk local sync started")
        result = await anydesk_service.fetch_sessions_from_local_endpoint(
            endpoint_url=settings.ANYDESK_LOCAL_SESSIONS_URL,
            timeout_seconds=settings.ANYDESK_LOCAL_SYNC_TIMEOUT_SECONDS,
            dry_run=settings.ANYDESK_LOCAL_SYNC_DRY_RUN,
        )

        if result.get("error"):
            logger.error("❌ AnyDesk local sync failed: %s", result["error"])
            return

        logger.info(
            "✅ AnyDesk local sync completed: total=%s imported=%s updated=%s matched=%s errors=%s",
            result.get("total", 0),
            result.get("imported", 0),
            result.get("updated", 0),
            result.get("matched", 0),
            len(result.get("errors") or []),
        )
    except Exception as exc:
        logger.error("❌ Unexpected AnyDesk local sync error: %s", exc)
