#!/usr/bin/env python3
"""
Script to migrate subscriptions and cleanup duplicate Free Plan entries
"""

from app import app
from models import db, SubscriptionPlan, Subscription

def migrate_and_cleanup_free_plans():
    """Migrate subscriptions from duplicate plans and then remove duplicates"""

    with app.app_context():
        # Find all free plans
        free_plans = SubscriptionPlan.query.filter_by(name='free').all()

        print(f"Found {len(free_plans)} Free Plan entries")

        if len(free_plans) > 1:
            # Keep the first one (or the one with subscriptions)
            for i, plan in enumerate(free_plans):
                subscription_count = len(plan.subscriptions)
                print(f"  Plan ID {plan.id}: {plan.display_name} - {subscription_count} subscriptions")

            # Keep the plan with the most subscriptions or the first one
            plans_with_subs = [(plan, len(plan.subscriptions)) for plan in free_plans]
            plans_with_subs.sort(key=lambda x: x[1], reverse=True)

            keep_plan = plans_with_subs[0][0]
            print(f"\nKeeping Plan ID {keep_plan.id} with {plans_with_subs[0][1]} subscriptions")

            # Migrate subscriptions from duplicate plans
            for plan, _ in plans_with_subs[1:]:
                print(f"\nMigrating {len(plan.subscriptions)} subscriptions from Plan ID {plan.id} to Plan ID {keep_plan.id}")

                # Update all subscriptions to use the plan we're keeping
                subscriptions_to_migrate = Subscription.query.filter_by(plan_id=plan.id).all()
                for sub in subscriptions_to_migrate:
                    print(f"  - Migrating subscription ID {sub.id}")
                    sub.plan_id = keep_plan.id

            # Commit the subscription migrations
            try:
                db.session.commit()
                print("\nSubscriptions migrated successfully!")
            except Exception as e:
                db.session.rollback()
                print(f"Error migrating subscriptions: {str(e)}")
                return False

            # Now delete the duplicate plans
            for plan, _ in plans_with_subs[1:]:
                print(f"Deleting duplicate Plan ID {plan.id}")
                db.session.delete(plan)

            try:
                db.session.commit()
                print("\nDuplicate Free Plans deleted successfully!")
            except Exception as e:
                db.session.rollback()
                print(f"Error deleting duplicate plans: {str(e)}")
                return False
        else:
            print("No duplicate Free Plans found")

        # Display all active plans
        print("\nCurrent active subscription plans:")
        plans = SubscriptionPlan.query.filter_by(is_active=True).order_by(SubscriptionPlan.price).all()
        for plan in plans:
            subscription_count = Subscription.query.filter_by(plan_id=plan.id).count()
            print(f"  - {plan.display_name} ({plan.name}): ${plan.price} - {subscription_count} subscriptions")

    return True

if __name__ == "__main__":
    migrate_and_cleanup_free_plans()