import requests
import json
import time
import os
from django.conf import settings

# 🚩 Note: Google Indexing ke liye 'google-auth' library install karni hogi
# Terminal mein: pip install google-auth
try:
    from google.oauth2 import service_account
    from google.auth.transport.requests import AuthorizedSession
except ImportError:
    service_account = None

def notify_indexnow(url_list):
    """
    Bing aur Yandex ko naye content ke baare mein inform karta hai.
    """
    key = "videshchalo14032026" 
    host = "www.videshchalo.com"
    
    payload = {
        "host": host,
        "key": key,
        "keyLocation": f"https://{host}/{key}.txt",
        "urlList": url_list
    }
    
    endpoints = [
        "https://www.bing.com/indexnow",
        "https://yandex.com/indexnow"
    ]
    
    headers = {
        "Content-Type": "application/json; charset=utf-8",
        "Host": "www.bing.com"
    }
    
    current_time = time.strftime('%Y-%m-%d %H:%M:%S')
    
    for url in endpoints:
        try:
            res = requests.post(url, json=payload, headers=headers if "bing" in url else None, timeout=20)
            if res.status_code in [200, 202]:
                print(f"[{current_time}] INDEXNOW SUCCESS: {url} | Status: {res.status_code}")
            else:
                print(f"[{current_time}] INDEXNOW FAIL: {url} | Status: {res.status_code}")
        except Exception as e:
            print(f"[{current_time}] INDEXNOW_ERROR: {str(e)}")

def notify_google_indexing(url, action="URL_UPDATED"):
    """
    Google Indexing API (Surgical Strike for Google Search)
    Action: URL_UPDATED (Post/Update ke liye) ya URL_DELETED (Job hatane ke liye)
    """
    current_time = time.strftime('%Y-%m-%d %H:%M:%S')
    
    # 1. Check if Library and Credentials exist
    creds_path = os.path.join(settings.BASE_DIR, 'google-indexing-credentials.json')
    
    if not service_account or not os.path.exists(creds_path):
        print(f"[{current_time}] GOOGLE_INDEXING_SKIP: Library missing or JSON file not found at {creds_path}")
        return

    try:
        # 2. Authenticate using Service Account
        scopes = ['https://www.googleapis.com/auth/indexing']
        credentials = service_account.Credentials.from_service_account_file(creds_path, scopes=scopes)
        authed_session = AuthorizedSession(credentials)

        # 3. Prepare Payload
        endpoint = "https://indexing.googleapis.com/v3/urlNotifications:publish"
        payload = {
            "url": url,
            "type": action
        }

        # 4. Send Request
        res = authed_session.post(endpoint, json=payload, timeout=20)
        
        if res.status_code == 200:
            print(f"[{current_time}] GOOGLE SUCCESS: {url} | Status: 200")
        else:
            print(f"[{current_time}] GOOGLE FAIL: {url} | Status: {res.status_code} | Msg: {res.text}")

    except Exception as e:
        print(f"[{current_time}] GOOGLE_ERROR: {str(e)}")