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

from app import app
from models import db, SubscriptionPlan

def cleanup_duplicate_free_plans():
    """Remove duplicate Free Plan entries"""

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

            # Delete the duplicates
            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 cleaned up successfully!")
            except Exception as e:
                db.session.rollback()
                print(f"Error cleaning up 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:
            print(f"  - {plan.display_name} ({plan.name}): ${plan.price}")

    return True

if __name__ == "__main__":
    cleanup_duplicate_free_plans()