#!/usr/bin/env python3
"""
Script to change a user's subscription to the free plan
"""

from app import app
from models import db, User, Subscription, SubscriptionPlan
from datetime import datetime, timedelta

def change_user_to_free(email):
    """Change user's subscription to free plan"""

    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})")

        # Find the free plan
        free_plan = SubscriptionPlan.query.filter_by(name='free').first()

        if not free_plan:
            print("❌ Free plan not found in database")
            return False

        print(f"✅ Found free plan (ID: {free_plan.id})")

        # Check current subscription
        current_subscription = Subscription.query.filter_by(
            user_id=user.id,
            status='active'
        ).first()

        if current_subscription:
            print(f"📊 Current subscription:")
            print(f"   - Plan: {current_subscription.plan.name} ({current_subscription.plan.display_name})")
            print(f"   - Monthly analyses used: {current_subscription.monthly_analyses_used}")
            print(f"   - Status: {current_subscription.status}")

            # Update to free plan
            old_plan = current_subscription.plan.name
            current_subscription.plan_id = free_plan.id
            current_subscription.stripe_subscription_id = None  # Free plan doesn't have Stripe subscription
            current_subscription.stripe_customer_id = None
            current_subscription.cancel_at_period_end = False
            current_subscription.monthly_analyses_used = 0  # Reset usage
            current_subscription.monthly_reset_date = datetime.utcnow() + timedelta(days=30)
            current_subscription.current_period_start = datetime.utcnow()
            current_subscription.current_period_end = datetime.utcnow() + timedelta(days=30)

            print(f"\n🔄 Changed from {old_plan} to free plan")
        else:
            # Create new free subscription
            current_subscription = Subscription(
                user_id=user.id,
                company_id=user.company_id,
                plan_id=free_plan.id,
                status='active',
                monthly_analyses_used=0,
                monthly_reset_date=datetime.utcnow() + timedelta(days=30),
                current_period_start=datetime.utcnow(),
                current_period_end=datetime.utcnow() + timedelta(days=30)
            )
            db.session.add(current_subscription)
            print("✅ Created new free subscription")

        # Commit changes
        try:
            db.session.commit()
            print(f"\n✅ Successfully changed {email} to free plan!")
            print(f"   - Monthly limit: {free_plan.features.get('monthly_analyses', 5)} analyses")
            print(f"   - Current usage: 0")
            print(f"   - Reset date: {current_subscription.monthly_reset_date.strftime('%Y-%m-%d')}")
            return True
        except Exception as e:
            db.session.rollback()
            print(f"❌ Error updating subscription: {str(e)}")
            return False

if __name__ == "__main__":
    email = "scott.barbour@yahoo.com"
    change_user_to_free(email)