# --- VIDESH CHALO: SMART BULK PINGER v2.0 ---
# Usage: python manage.py shell < bulk_index_ping.py
# Features: Time filtering to prevent spamming old links.

import os
import django
from django.urls import reverse
from django.utils import timezone
from datetime import timedelta

# 🛡️ Models Import
from jobs.models import Job, NewsPost
from blog.models import BlogPost
from jobs.indexnow_utils import notify_indexnow, notify_google_indexing

def run_smart_bulk_pinger(days_back=2):
    print("\n" + "="*60)
    print(f"🚀 VIDESH CHALO: Smart Pinger (Last {days_back} days)")
    print("="*60)

    base_url = "https://www.videshchalo.com"
    all_urls = []
    start_date = timezone.now() - timedelta(days=days_back)

    # 1. STATIC PAGES (Hamesha included - 10-12 links hi hain)
    static_names = ['home', 'news_list', 'blog_list', 'referral_program', 'ai_resume_builder']
    for name in static_names:
        try:
            all_urls.append(f"{base_url}{reverse(name)}")
        except: continue

    # 2. RECENT JOBS
    recent_jobs = Job.objects.filter(is_approved=True, updated_at__gte=start_date).only('slug')
    for j in recent_jobs:
        all_urls.append(f"{base_url}/{j.slug}/")

    # 3. RECENT NEWS
    recent_news = NewsPost.objects.filter(status='published', updated_at__gte=start_date).only('slug', 'category')
    for n in recent_news:
        path = reverse('news_detail', kwargs={'category_slug': n.category, 'slug': n.slug})
        all_urls.append(f"{base_url}{path}")

    # 4. RECENT BLOGS
    recent_blogs = BlogPost.objects.filter(is_published=True, updated_at__gte=start_date).only('slug', 'category')
    for b in recent_blogs:
        path = reverse('blog_detail', kwargs={'category': b.category, 'slug': b.slug})
        all_urls.append(f"{base_url}{path}")

    total_links = len(all_urls)
    print(f"🔗 Found {total_links} updated/static links.")

    if total_links > 0:
        # 📡 BING / YANDEX (Batch Support - 10,000 URLs allowed in one ping)
        print("📡 Notifying Bing & Yandex...")
        notify_indexnow(all_urls)

        # 🔍 GOOGLE (Note: Google does NOT support bulk lists in one call)
        # Isliye hum Google ko sirf top 5 latest news bhejenge spam se bachne ke liye
        print("🔍 Notifying Google (Top 5 Recent)...")
        for url in all_urls[:5]:
             notify_google_indexing(url)
             
        print(f"\n✨ SUCCESS: Smart Sync completed!")
    else:
        print("\nℹ️ No new updates found in the last few days.")

# Run execution
if __name__ == "__main__" or "django" in str(getattr(os, 'environ', {})):
    # Aap 'days_back=7' karke ek hafte ka data bhi bhej sakte hain
    run_smart_bulk_pinger(days_back=2)