import time
from functools import wraps
import json
import re

# Gemini key now comes from the dynamic credential store (master admin
# panel → Credentials), resolved lazily on each call.
from core.utils.gemini import model


def explain_reason(text, retries=3):
    for attempt in range(retries):
        try:
            prompt = f"Rewrite this leave reason in simple English: '{text}'"
            response = model.generate_content(prompt)
            return response.text.strip()

        except Exception as e:
            if "429" in str(e) and attempt < retries - 1:
                wait_time = 60 * (attempt + 1)  # Wait 60, 120, 180 seconds
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                print(f"Error: {e}")
                return text  # Fallback to original

    return text


def moderate_chat_content(content, student_name="Student", retries=3):
    """
    Moderate chat content to ensure it's academic appropriate.
    Returns dict with:
    - is_academic: bool
    - reason: str (why rejected)
    - suggestions: str (alternative suggestions)
    - category: str (type of violation)
    - confidence: float
    - message: str (user-friendly message)
    """

    prompt = f"""
    You are an AI content moderator for a school chat app. Student {student_name} sent a message: "{content}"
    
    Determine if this message is APPROPRIATE for academic/school-related chat between students.
    
    ✅ ALLOWED topics (academic appropriate):
    - Homework, assignments, projects
    - Class schedules, exams, tests
    - Study groups, subject discussions
    - School events, extracurricular activities
    - Asking for help with studies
    - Sharing notes, books, resources
    - General school-related questions
    - Friendly greetings ("hi", "hello", "good morning")
    - Asking about classmates' wellbeing
    
    ❌ REJECTED topics (not academic appropriate):
    - Romantic/relationship talk ("I love you", "dating", "crush")
    - Planning trips, parties, hangouts outside school
    - Bullying, harassment, personal attacks
    - Swearing, profanity, inappropriate language
    - Sharing personal contact info (phone numbers, addresses)
    - Sharing social media handles (Instagram, WhatsApp, Snapchat)
    - Gossip about teachers or students
    - Planning to skip school/classes
    - Discussions about drugs, alcohol, violence
    - Chain messages, spam
    - Commercial/promotional content
    
    Respond in JSON format:
    {{
        "is_academic": true/false,
        "category": "academic" or "romantic" or "social" or "inappropriate" or "personal_info" or "spam",
        "reason": "Brief explanation why rejected (if rejected)",
        "suggestions": "Suggested appropriate alternative message (if rejected)",
        "confidence": 0.0 to 1.0
    }}
    """

    for attempt in range(retries):
        try:
            response = model.generate_content(prompt)
            response_text = response.text.strip()

            # Extract JSON from response (in case there's extra text)
            if "```json" in response_text:
                response_text = response_text.split("```json")[1].split("```")[0]
            elif "```" in response_text:
                response_text = response_text.split("```")[1].split("```")[0]

            result = json.loads(response_text)

            # Add user-friendly message
            if result.get("is_academic", False):
                result["message"] = "Message approved for academic chat"
            else:
                category = result.get("category", "inappropriate")
                messages = {
                    "romantic": "Romantic messages are not allowed in academic chat. Please keep conversations focused on studies.",
                    "social": "Social gathering planning is not allowed. Please discuss school-related topics only.",
                    "inappropriate": "This message contains inappropriate content for academic chat.",
                    "personal_info": "Sharing personal contact information is not allowed for safety reasons.",
                    "spam": "Please avoid sending promotional or spam messages.",
                }
                result["message"] = messages.get(
                    category,
                    "This message is not appropriate for academic chat. Please keep conversations school-related.",
                )

            return result

        except json.JSONDecodeError as e:
            print(f"JSON decode error: {e}, response: {response_text}")
            # Fallback response
            return {
                "is_academic": False,
                "category": "error",
                "reason": "Unable to moderate content",
                "suggestions": "Please keep your message school-related and appropriate.",
                "confidence": 0.5,
                "message": "Unable to verify message content. Please keep conversations academic-focused.",
            }

        except Exception as e:
            if "429" in str(e) and attempt < retries - 1:
                wait_time = 60 * (attempt + 1)
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                print(f"Error in moderate_chat_content: {e}")
                # Fallback to allow message if AI fails (to not block users)
                return {
                    "is_academic": True,  # Allow by default if AI fails
                    "category": "fallback",
                    "reason": None,
                    "suggestions": None,
                    "confidence": 0.0,
                    "message": "Message approved",
                }

    return {
        "is_academic": True,  # Allow after retries
        "category": "fallback",
        "reason": None,
        "suggestions": None,
        "confidence": 0.0,
        "message": "Message approved",
    }


# Optional: Quick keyword-based pre-filter to reduce AI API calls
def quick_keyword_filter(content):
    """
    Quick pre-filter using keywords before calling AI
    Returns True if message should be rejected immediately
    """
    content_lower = content.lower()

    # Rejection patterns (fast check)
    rejection_patterns = [
        r"\b(i|l)(\s+)?love\s+you\b",
        r"\b(dating|date\s+me|boyfriend|girlfriend|crush)\b",
        r"\b(party|hangout|meet\s+up|outside\s+school)\b",
        r"\b(instagram|whatsapp|snapchat|facebook|social\s+media)\b",
        r"\b(phone\s*number|contact\s+number|call\s+me)\b",
        r"\b(skip\s+class|bunk|absent\s+intentionally)\b",
        r"\b(fuck|shit|damn|hell)\b",
        r"\b(beer|wine|drink|smoke|weed|drugs?)\b",
    ]

    for pattern in rejection_patterns:
        if re.search(pattern, content_lower):
            return True

    return False
