"""
Celery tasks for billing and credit management.
"""

from __future__ import annotations

import logging

from ..celery_app import celery_app

logger = logging.getLogger(__name__)


@celery_app.task
def reset_free_tier_credits() -> dict:
    """
    Reset ai_credits_used to 0 for all free-plan organisations.

    Runs on the 1st of each month at 00:05 UTC via Celery beat.
    Paid plans (basic, pro) are reset by the Stripe invoice.paid webhook
    instead, so they are excluded here.
    """
    import datetime as dt
    from ..db import session_scope
    from ..public_models import Organization
    from sqlalchemy import text

    logger.info("[reset_free_tier_credits] Running monthly credit reset for free orgs")

    with session_scope() as session:
        result = session.execute(
            text("""
                UPDATE public.organizations
                SET ai_credits_used = 0,
                    ai_credits_reset_at = :now
                WHERE plan = 'free'
                  AND ai_credits_used > 0
            """),
            {"now": dt.datetime.utcnow()},
        )
        count = result.rowcount

    logger.info("[reset_free_tier_credits] Reset credits for %d free orgs", count)
    return {"status": "ok", "orgs_reset": count}
