"""
NOMAZRA Celery Tasks — Production background jobs.
- Reminder push notification delivery (every 60s)
- Daily 8PM engagement notification with AI legal tips
- Stale session cleanup (daily)
"""
import logging
import random
from datetime import timedelta

from celery import shared_task
from django.utils import timezone
from django.conf import settings

logger = logging.getLogger(__name__)


# ──────────────────── DAILY LEGAL TIPS ────────────────────
# Rotated daily at 8 PM to keep users engaged
DAILY_TIPS = [
    {
        "title": "Did you know?",
        "body": "In most countries, you have the right to remain silent during police questioning. Open NOMAZRA to learn your rights.",
    },
    {
        "title": "Legal Tip of the Day",
        "body": "Always read contracts fully before signing. NOMAZRA can analyze any contract in seconds — upload yours now.",
    },
    {
        "title": "Protect Yourself",
        "body": "Statute of limitations can expire! Use NOMAZRA's Statute Checker to see if your claim is still valid.",
    },
    {
        "title": "Know Your Rights",
        "body": "Employees in most countries can't be fired for reporting safety violations. Check your workplace rights on NOMAZRA.",
    },
    {
        "title": "Legal Fact",
        "body": "Verbal agreements can be legally binding in many jurisdictions. Ask NOMAZRA about contract law in your country.",
    },
    {
        "title": "Tenant Rights",
        "body": "Your landlord must give proper notice before entering your home. Check eviction laws on NOMAZRA.",
    },
    {
        "title": "Consumer Protection",
        "body": "Bought a defective product? You may be entitled to a refund or replacement. Ask NOMAZRA about your consumer rights.",
    },
    {
        "title": "Immigration Update",
        "body": "Immigration laws change frequently. Stay informed — ask NOMAZRA about visa requirements for your situation.",
    },
    {
        "title": "Family Law Tip",
        "body": "Child custody decisions prioritize the child's best interest. Learn more about family law on NOMAZRA.",
    },
    {
        "title": "Workplace Rights",
        "body": "Unpaid overtime? Many countries require employers to pay 1.5x for extra hours. Check labor laws on NOMAZRA.",
    },
    {
        "title": "Traffic Law",
        "body": "Know what to do at a traffic stop. Check your rights with NOMAZRA's Know Your Rights cards.",
    },
    {
        "title": "Legal Document Tip",
        "body": "Never sign a document you don't understand. Upload it to NOMAZRA for instant AI analysis.",
    },
    {
        "title": "Property Rights",
        "body": "Buying property? Due diligence is critical. Ask NOMAZRA about property law in your jurisdiction.",
    },
    {
        "title": "Tax Reminder",
        "body": "Tax deadlines vary by country. Use NOMAZRA to check important legal dates and set reminders.",
    },
    {
        "title": "Digital Rights",
        "body": "Your online privacy is protected by law in many countries. Ask NOMAZRA about data protection rights.",
    },
    {
        "title": "Criminal Law Fact",
        "body": "You're presumed innocent until proven guilty in most legal systems. Know your criminal defense rights on NOMAZRA.",
    },
    {
        "title": "Business Law Tip",
        "body": "Starting a business? Legal structure matters — LLC, sole proprietorship, or corporation? Ask NOMAZRA.",
    },
    {
        "title": "Divorce Rights",
        "body": "Going through a divorce? Know your rights regarding property division, custody, and support. Ask NOMAZRA.",
    },
    {
        "title": "Legal Aid",
        "body": "Can't afford a lawyer? Many countries offer free legal aid. Check emergency info on NOMAZRA.",
    },
    {
        "title": "Harassment Laws",
        "body": "Workplace harassment is illegal. Document everything and know your reporting options. Check on NOMAZRA.",
    },
    {
        "title": "Contract Basics",
        "body": "Every valid contract needs offer, acceptance, and consideration. Draft professional contracts with NOMAZRA.",
    },
    {
        "title": "Your Voice Matters",
        "body": "Try NOMAZRA's voice feature — ask any legal question by speaking. It's faster and just as accurate.",
    },
    {
        "title": "Cost Estimation",
        "body": "Wondering how much a legal matter might cost? Use NOMAZRA's Cost Estimator for instant estimates.",
    },
    {
        "title": "Legal Glossary",
        "body": "Confused by legal jargon? NOMAZRA's glossary explains 1000+ legal terms in plain language.",
    },
    {
        "title": "Multi-Country Law",
        "body": "Laws differ across borders. NOMAZRA covers 180+ countries — compare laws across jurisdictions instantly.",
    },
    {
        "title": "Emergency Contacts",
        "body": "NOMAZRA has emergency legal hotlines for 140+ countries. Access them anytime, even offline.",
    },
    {
        "title": "Bookmark Important Advice",
        "body": "Found useful legal info? Bookmark it in NOMAZRA so you never lose important legal advice.",
    },
    {
        "title": "Set Legal Reminders",
        "body": "Court date coming up? Filing deadline? Set a reminder in NOMAZRA and never miss an important date.",
    },
    {
        "title": "PDF Export",
        "body": "Need legal advice in writing? Export any NOMAZRA conversation as a professional PDF document.",
    },
    {
        "title": "Legal Awareness",
        "body": "Knowing your rights is the first step to protecting them. Explore NOMAZRA's Know Your Rights cards today.",
    },
]


@shared_task(name='nomazra.tasks.check_and_send_reminders')
def check_and_send_reminders():
    """
    Check for due reminders and send FCM push notifications.
    Runs every 60 seconds via Celery Beat.
    """
    from .models import Reminder
    from . import fcm_service

    now = timezone.now()
    # Find reminders that are due (remind_at <= now) and not completed
    # Also skip reminders already past by more than 24 hours (stale)
    cutoff = now - timedelta(hours=24)

    due_reminders = Reminder.objects.filter(
        remind_at__lte=now,
        remind_at__gte=cutoff,
        is_completed=False,
    ).select_related('user')

    sent_count = 0
    for reminder in due_reminders:
        user = reminder.user
        fcm_token = getattr(user, 'fcm_token', None)

        if not fcm_token:
            logger.info("No FCM token for user %s, skipping reminder %s", user.id, reminder.id)
            continue

        try:
            result = fcm_service.notify_reminder(
                fcm_token,
                reminder.title,
                reminder.description or f"Your {reminder.get_reminder_type_display()} reminder is due.",
            )
            if result:
                sent_count += 1
                logger.info("Sent reminder notification: %s to user %s", reminder.title, user.id)

            # Mark as completed so we don't resend
            reminder.is_completed = True
            reminder.save(update_fields=['is_completed'])

        except Exception as e:
            logger.error("Failed to send reminder %s: %s", reminder.id, e)

    if sent_count > 0:
        logger.info("Sent %d reminder notifications", sent_count)

    return f"Processed {due_reminders.count()} reminders, sent {sent_count}"


@shared_task(name='nomazra.tasks.daily_engagement_notification')
def daily_engagement_notification():
    """
    Send daily 8 PM engagement notification to all users with FCM tokens.
    AI-powered legal tips, feature highlights, and law awareness.
    Uses OpenAI to generate a personalized tip when possible, falls back to curated tips.
    """
    from django.contrib.auth import get_user_model
    from . import fcm_service

    User = get_user_model()

    # Get all users who have FCM tokens (active app users)
    users_with_tokens = User.objects.filter(
        fcm_token__isnull=False,
    ).exclude(fcm_token='').values_list('fcm_token', flat=True)

    tokens = list(users_with_tokens)
    if not tokens:
        logger.info("No users with FCM tokens for daily engagement")
        return "No tokens found"

    # Pick today's tip (deterministic per day so all users get same tip)
    day_of_year = timezone.now().timetuple().tm_yday
    tip = DAILY_TIPS[day_of_year % len(DAILY_TIPS)]

    # Try AI-generated tip for more variety
    ai_tip = _generate_ai_daily_tip()
    if ai_tip:
        tip = ai_tip

    # Send to all users in batches of 500 (FCM limit)
    total_sent = 0
    batch_size = 500
    for i in range(0, len(tokens), batch_size):
        batch = tokens[i:i + batch_size]
        try:
            result = fcm_service.send_to_multiple(
                batch,
                tip['title'],
                tip['body'],
                data={'type': 'daily_tip', 'action': 'open_home'},
            )
            if result:
                total_sent += getattr(result, 'success_count', len(batch))
        except Exception as e:
            logger.error("Failed to send daily engagement batch: %s", e)

    logger.info("Daily engagement: sent to %d/%d users", total_sent, len(tokens))
    return f"Sent daily tip to {total_sent}/{len(tokens)} users"


def _generate_ai_daily_tip():
    """
    Generate a daily legal tip using OpenAI.
    Falls back to None if API fails (curated tips used instead).
    """
    try:
        import openai
        import os

        client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

        # Pick a random legal topic for variety
        topics = [
            "tenant rights", "employment law", "consumer protection",
            "traffic law", "family law", "immigration", "criminal defense",
            "contract law", "property rights", "tax obligations",
            "digital privacy", "workplace safety", "divorce proceedings",
            "small claims court", "intellectual property", "debt collection",
            "medical malpractice", "insurance claims", "business formation",
            "estate planning",
        ]
        topic = random.choice(topics)

        response = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=[
                {
                    'role': 'system',
                    'content': (
                        'You are NOMAZRA, an AI legal assistant. Generate a short, engaging push notification '
                        'about legal rights/tips. Must be under 120 characters for body. Be informative and '
                        'encourage users to learn more. Never mention GPT, OpenAI, or ChatGPT. '
                        'Return JSON: {"title": "...", "body": "..."}'
                    ),
                },
                {
                    'role': 'user',
                    'content': f'Generate a push notification tip about {topic}.',
                },
            ],
            temperature=0.8,
            max_tokens=100,
            response_format={"type": "json_object"},
        )

        import json
        tip_data = json.loads(response.choices[0].message.content)
        if 'title' in tip_data and 'body' in tip_data:
            return tip_data

    except Exception as e:
        logger.debug("AI tip generation failed (using curated): %s", e)

    return None


@shared_task(name='nomazra.tasks.cleanup_stale_voice_sessions')
def cleanup_stale_voice_sessions():
    """
    Clean up voice sessions that were never properly ended.
    Runs daily. Sets duration to 0 for sessions older than 2 hours with no duration.
    """
    from .models import VoiceSession

    cutoff = timezone.now() - timedelta(hours=2)
    stale = VoiceSession.objects.filter(
        created_at__lt=cutoff,
        duration_seconds=0,
    )
    count = stale.count()
    if count > 0:
        stale.update(duration_seconds=0)
        logger.info("Cleaned up %d stale voice sessions", count)

    return f"Cleaned {count} stale sessions"


@shared_task(name='nomazra.tasks.weekly_engagement_summary')
def weekly_engagement_summary():
    """
    Send weekly summary to active users — how many queries they asked,
    features they used, and suggestions for features they haven't tried.
    """
    from django.contrib.auth import get_user_model
    from .models import Message, Document, VoiceSession
    from . import fcm_service

    User = get_user_model()
    week_ago = timezone.now() - timedelta(days=7)

    users_with_tokens = User.objects.filter(
        fcm_token__isnull=False,
    ).exclude(fcm_token='')

    sent_count = 0
    for user in users_with_tokens:
        # Count weekly activity
        queries = Message.objects.filter(
            conversation__user=user,
            role='user',
            created_at__gte=week_ago,
        ).count()

        docs = Document.objects.filter(
            user=user,
            created_at__gte=week_ago,
        ).count()

        voice = VoiceSession.objects.filter(
            user=user,
            created_at__gte=week_ago,
        ).count()

        if queries == 0 and docs == 0 and voice == 0:
            # Inactive user — send re-engagement
            body = "You haven't used NOMAZRA this week. Your legal questions deserve expert answers — come back anytime!"
            title = "We miss you!"
        else:
            # Active user — send summary
            parts = []
            if queries > 0:
                parts.append(f"{queries} legal queries")
            if docs > 0:
                parts.append(f"{docs} documents analyzed")
            if voice > 0:
                parts.append(f"{voice} voice sessions")

            body = f"This week: {', '.join(parts)}. Keep exploring your legal rights!"
            title = "Your Weekly Legal Summary"

            # Suggest unused features
            if docs == 0:
                body += " Try uploading a document for instant AI analysis."
            elif voice == 0:
                body += " Try voice mode — ask legal questions by speaking."

        try:
            fcm_service.send_notification(
                user.fcm_token,
                title,
                body[:180],  # FCM body limit
                data={'type': 'weekly_summary', 'action': 'open_home'},
            )
            sent_count += 1
        except Exception as e:
            logger.error("Weekly summary failed for user %s: %s", user.id, e)

    logger.info("Weekly summary sent to %d users", sent_count)
    return f"Sent weekly summary to {sent_count} users"
