import random
import logging

_logger = logging.getLogger(__name__)


class ContentSourceGate:
    """Determines review requirements based on content source.

    - AI-generated, not IELTS-certified → mandatory full review
    - IELTS-certified entity content → spot-check (random 10% sampling)
    - Otherwise → auto-approve
    """

    SPOT_CHECK_RATE = 0.10

    @classmethod
    def check(cls, resource):
        if resource.ai_generated and not resource.ielts_certified:
            return 'mandatory_review'
        if hasattr(resource, 'ielts_certified') and resource.ielts_certified:
            if random.random() < cls.SPOT_CHECK_RATE:
                return 'spot_check'
            return 'auto_approve'
        return 'auto_approve'

    @classmethod
    def apply_gate(cls, resource):
        result = cls.check(resource)
        if result == 'mandatory_review':
            resource.write({'review_status': 'pending', 'approved': False})
        elif result == 'spot_check':
            resource.write({'review_status': 'pending', 'approved': False})
        else:
            resource.write({'review_status': 'approved', 'approved': True})
        return result
