#!/usr/bin/env python3
"""
Script to set a user's analysis usage to a specific number for testing
"""

from app import app
from models import db, User, Subscription

def set_user_usage(email, usage_count):
    """Set user's monthly usage to specific count"""

    with app.app_context():
        # Find the user
        user = User.query.filter_by(email=email).first()

        if not user:
            print(f"❌ User with email {email} not found")
            return False

        print(f"✅ Found user: {user.username} (ID: {user.id})")

        # Get user's subscription
        subscription = Subscription.query.filter_by(
            user_id=user.id,
            status='active'
        ).first()

        if not subscription:
            print("❌ No active subscription found")
            return False

        # Get the monthly limit
        limit = subscription.plan.features.get('monthly_analyses', 5)

        print(f"📊 Current subscription:")
        print(f"   - Plan: {subscription.plan.display_name}")
        print(f"   - Monthly limit: {limit}")
        print(f"   - Current usage: {subscription.monthly_analyses_used}")

        # Set usage to specified count
        old_usage = subscription.monthly_analyses_used
        subscription.monthly_analyses_used = usage_count

        try:
            db.session.commit()
            print(f"\n✅ Set usage successfully!")
            print(f"   - Usage was: {old_usage}/{limit}")
            print(f"   - Usage now: {usage_count}/{limit}")
            print(f"   - Remaining analyses: {limit - usage_count}")

            if usage_count >= limit:
                print(f"   ⚠️  User will see upgrade options on next attempt")
            else:
                print(f"   ✅ User can perform {limit - usage_count} more analyses before seeing upgrade options")

            return True
        except Exception as e:
            db.session.rollback()
            print(f"❌ Error setting usage: {str(e)}")
            return False

if __name__ == "__main__":
    email = "scott.barbour@yahoo.com"
    set_user_usage(email, 4)  # Set to 4 out of 5