from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.business.distributor.models import BrandAmbassadorEligibility
from apps.business.distributor.services.ambassador_service import refresh_brand_ambassadors
from apps.business.schemes.models import OpportunityBundle


TOP_N = 48  # Always return at most this many Executive Directors


class BrandAmbassadorListView(APIView):
    permission_classes = [permissions.IsAdminUser]

    def get(self, request):
        opportunity_bundle_id = request.query_params.get('opportunity_bundle') or request.query_params.get('opportunity_bundle_id')
        threshold_raw = request.query_params.get('threshold')
        refresh_raw = str(request.query_params.get('refresh', '')).lower()

        try:
            threshold = int(threshold_raw) if threshold_raw else 100
            if threshold <= 0:
                threshold = 100
        except Exception:
            threshold = 100

        refresh = refresh_raw in {'1', 'true', 'yes'}
        refresh_result = None
        if refresh:
            refresh_result = refresh_brand_ambassadors(min_distributor_ids=threshold, opportunity_bundle_id=opportunity_bundle_id)

        queryset = BrandAmbassadorEligibility.objects.filter(is_active=True).select_related('user', 'opportunity_bundle')
        if opportunity_bundle_id:
            queryset = queryset.filter(opportunity_bundle_id=opportunity_bundle_id)

        queryset = queryset.order_by('-distributor_count', 'qualified_at')[:TOP_N]

        executive_directors = []
        for idx, row in enumerate(queryset, start=1):
            first_name = (getattr(row.user, 'first_name', '') or '').strip()
            last_name = (getattr(row.user, 'last_name', '') or '').strip()
            full_name = f'{first_name} {last_name}'.strip() or row.user.mobile or row.user.email or str(row.user_id)

            executive_directors.append({
                'rank': idx,
                'user_id': str(row.user_id),
                'name': full_name,
                'mobile': row.user.mobile,
                'email': row.user.email,
                'role': row.user.role,
                'opportunity_bundle_id': str(row.opportunity_bundle_id),
                'opportunity_bundle_name': row.opportunity_bundle.name,
                'distributor_count': row.distributor_count,
                'qualified_at': row.qualified_at,
                'last_distributor_created_at': row.last_distributor_created_at,
            })

        schemes = [
            {
                'id': str(s.id),
                'name': s.name,
                'is_active': s.is_active,
            }
            for s in OpportunityBundle.objects.all().order_by('name')
        ]

        return Response(
            {
                'opportunity_bundles': schemes,
                'schemes': schemes,
                'selected_opportunity_bundle': opportunity_bundle_id,
                'selected_scheme': opportunity_bundle_id,
                'threshold': threshold,
                'executiveDirectors': executive_directors,
                'summary': {
                    'count': len(executive_directors),
                },
                'refresh_result': refresh_result,
            },
            status=status.HTTP_200_OK,
        )
