import asyncio
from datetime import datetime, timedelta

from app.tasks.celery_app import celery_app


@celery_app.task
def cleanup_expired_video_urls():
    """Run hourly. Clear expired video URL tokens."""
    asyncio.run(_cleanup_urls())


async def _cleanup_urls():
    from app.models.base import async_session
    from app.models.generation_record import GenerationRecord
    from sqlalchemy import update

    async with async_session() as db:
        now = datetime.now()
        await db.execute(
            update(GenerationRecord)
            .where(
                GenerationRecord.video_url_expires_at.isnot(None),
                GenerationRecord.video_url_expires_at < now,
                GenerationRecord.deleted_at.is_(None),
            )
            .values(video_url_expires_at=None)
        )
        await db.commit()


@celery_app.task
def cleanup_old_notifications():
    """Run daily. Delete read notifications older than 30 days."""
    asyncio.run(_cleanup_notifications())


async def _cleanup_notifications():
    from app.models.base import async_session
    from app.models.notification import Notification
    from sqlalchemy import delete

    async with async_session() as db:
        cutoff = datetime.now() - timedelta(days=30)
        await db.execute(
            delete(Notification).where(
                Notification.is_read == True,
                Notification.created_at < cutoff,
            )
        )
        await db.commit()
