"""Periodic purge of sync_logs older than SYNC_LOG_RETENTION_DAYS (design: 30 days)."""

from __future__ import annotations

import asyncio
import logging

from server.infrastructure.database.session import AsyncSessionLocal
from server.infrastructure.database.sync_log_repo import (
    SYNC_LOG_RETENTION_DAYS,
    SyncLogRepositoryImpl,
)

logger = logging.getLogger("nexus.sync_log_purge")

PURGE_INTERVAL_SECONDS = 24 * 3600


async def purge_stale_sync_logs() -> int:
    """Delete sync_logs rows older than retention window. Returns rows removed."""
    async with AsyncSessionLocal() as session:
        repo = SyncLogRepositoryImpl(session)
        return await repo.purge_older_than(retention_days=SYNC_LOG_RETENTION_DAYS)


async def sync_log_purge_loop() -> None:
    """Run daily on primary worker; also invoked once at API startup."""
    while True:
        try:
            count = await purge_stale_sync_logs()
            if count:
                logger.info(
                    "Sync log purge: removed %s row(s) older than %s days",
                    count,
                    SYNC_LOG_RETENTION_DAYS,
                )
            await asyncio.sleep(PURGE_INTERVAL_SECONDS)
        except asyncio.CancelledError:
            raise
        except Exception:
            logger.exception("Sync log purge loop error")
            await asyncio.sleep(PURGE_INTERVAL_SECONDS)
