"""
Management command to get account plan limits
Usage: python manage.py get_account_limits dev@igny8.com scale@igny8.com
"""
from django.core.management.base import BaseCommand
from igny8_core.auth.models import Account, Plan, User
from django.db.models import Q


class Command(BaseCommand):
    help = 'Get plan limits for specified accounts'

    def add_arguments(self, parser):
        parser.add_argument('emails', nargs='+', type=str, help='Email addresses of accounts to check')

    def handle(self, *args, **options):
        emails = options['emails']
        
        # Table header
        print("\n" + "="*120)
        print("PLAN LIMITS COMPARISON TABLE")
        print("="*120 + "\n")
        
        # Get all limit fields from Plan model
        limit_fields = {
            'General': [
                ('max_users', 'Max Users'),
                ('max_sites', 'Max Sites'),
            ],
            'Planner': [
                ('max_keywords', 'Max Keywords'),
                ('max_clusters', 'Max Clusters'),
                ('max_content_ideas', 'Max Content Ideas'),
                ('daily_cluster_limit', 'Daily Cluster Limit'),
            ],
            'Writer': [
                ('monthly_word_count_limit', 'Monthly Word Count Limit'),
                ('daily_content_tasks', 'Daily Content Tasks'),
            ],
            'Images': [
                ('monthly_image_count', 'Monthly Image Count'),
                ('daily_image_generation_limit', 'Daily Image Generation Limit'),
            ],
            'AI Credits': [
                ('monthly_ai_credit_limit', 'Monthly AI Credit Limit'),
                ('monthly_cluster_ai_credits', 'Monthly Cluster AI Credits'),
                ('monthly_content_ai_credits', 'Monthly Content AI Credits'),
                ('monthly_image_ai_credits', 'Monthly Image AI Credits'),
            ],
        }
        
        accounts_data = []
        
        for email in emails:
            account = Account.objects.filter(users__email=email).first()
            if not account:
                self.stdout.write(self.style.WARNING(f'Account not found for {email}'))
                accounts_data.append({
                    'email': email,
                    'account': None,
                    'plan': None,
                    'limits': {}
                })
                continue
            
            plan = account.plan if account else None
            limits = {}
            
            if plan:
                for category, fields in limit_fields.items():
                    limits[category] = {}
                    for field_name, field_display in fields:
                        value = getattr(plan, field_name, None)
                        limits[category][field_name] = value
                
                # Add effective credits
                limits['AI Credits']['credits_per_month'] = plan.get_effective_credits_per_month()
            
            accounts_data.append({
                'email': email,
                'account': account,
                'plan': plan,
                'limits': limits
            })
        
        # Print table header
        header = f"{'Limit Category':<20} {'Limit Name':<45} "
        for acc_data in accounts_data:
            email_short = acc_data['email'].split('@')[0].upper()
            header += f"{email_short:<20} "
        print(header)
        print("-" * 120)
        
        # Print table rows
        for category, fields in limit_fields.items():
            print(f"\n{self.style.BOLD(category.upper())}")
            for field_name, field_display in fields:
                row = f"  {field_display:<43} "
                for acc_data in accounts_data:
                    if acc_data['plan']:
                        value = acc_data['limits'].get(category, {}).get(field_name, 'N/A')
                        row += f"{str(value):<20} "
                    else:
                        row += f"{'NO PLAN':<20} "
                print(row)
        
        # Print effective credits
        print(f"\n  {'Credits Per Month (Effective)':<43} ", end="")
        for acc_data in accounts_data:
            if acc_data['plan']:
                value = acc_data['limits'].get('AI Credits', {}).get('credits_per_month', 'N/A')
                print(f"{str(value):<20} ", end="")
            else:
                print(f"{'NO PLAN':<20} ", end="")
        print()
        
        # Print account details
        print("\n" + "="*120)
        print("ACCOUNT DETAILS")
        print("="*120 + "\n")
        
        for acc_data in accounts_data:
            print(f"Email: {acc_data['email']}")
            if acc_data['account']:
                print(f"  Account Name: {acc_data['account'].name}")
                print(f"  Account Slug: {acc_data['account'].slug}")
                if acc_data['plan']:
                    print(f"  Plan Name: {acc_data['plan'].name}")
                    print(f"  Plan Slug: {acc_data['plan'].slug}")
                    print(f"  Plan Price: ${acc_data['plan'].price}")
                    print(f"  Plan ID: {acc_data['plan'].id}")
                else:
                    print(f"  Plan: {self.style.ERROR('NO PLAN ASSIGNED')}")
            else:
                print(f"  Account: {self.style.ERROR('NOT FOUND')}")
            print()
        
        # Summary
        print("="*120)
        print("SUMMARY")
        print("="*120)
        print(f"Total accounts checked: {len(emails)}")
        accounts_with_plans = sum(1 for acc in accounts_data if acc['plan'])
        print(f"Accounts with plans: {accounts_with_plans}")
        print(f"Accounts without plans: {len(emails) - accounts_with_plans}")
        print()

