from datetime import datetime
from .. import db

def ensure_quota_and_increment(user):
    # Reset monthly counter if month rolled over
    now = datetime.utcnow()
    if user.month_anchor and (user.month_anchor.year != now.year or user.month_anchor.month != now.month):
        user.month_anchor = now
        user.monthly_lookups = 0

    limit = (user.plan.monthly_lookup_limit if user.plan else 25)
    if user.monthly_lookups >= limit:
        return False, f"Monthly lookup limit reached ({limit}). Consider upgrading your plan."
    user.monthly_lookups += 1
    db.session.commit()
    return True, None
