from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from serp.models import Keyword, Groups, Competitors
from django.http import JsonResponse
import requests
import json
import os
from django.conf import settings
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from datetime import date
import time



RAPID_API_KEY = "f6d117df33msh3da512288c98c0cp17197ajsn973cb4ee4f5f"
TRAFFIC_THREAD_LIMIT = 5


# def get_traffic_monthly_avg(site_url, max_attempts=3):
#     url = "https://ahrefs2.p.rapidapi.com/traffic"
#     headers = {
#         "x-rapidapi-key": RAPID_API_KEY,
#         "x-rapidapi-host": "ahrefs2.p.rapidapi.com"
#     }
#     params = {"url": site_url, "mode": "exact"}

#     for attempt in range(1, max_attempts + 1):
#         try:
#             response = requests.get(url, headers=headers, params=params, timeout=60)
#             response.raise_for_status()
#             data = response.json()
#             return data.get("trafficMonthlyAvg", 0)
#         except requests.exceptions.RequestException as e:
#             print(f"[Attempt {attempt}] Request failed for {site_url}: {e}")
#             time.sleep(2 * attempt)
#         except ValueError as e:
#             print(f"[Attempt {attempt}] Invalid JSON response: {e}")
#             break
#     return 0


# @api_view(["GET"])
# @permission_classes([AllowAny])
# def keywordTaffic(request):

    # """
    # Cron endpoint: fetches traffic for every keyword with a ranked_url
    # and updates the `traffic` field in the database.
    # """
    # try:
    #     # ←—— Everything in here is your “happy path”
    #     keywords = Keyword.objects.exclude(ranked_url__isnull=True).exclude(ranked_url="")

    #     for kw in keywords:
    #         traffic = get_traffic_monthly_avg(kw.ranked_url)
    #         Keyword.objects.filter(id=kw.id).update(traffic=traffic)
    #         print(f"Updated {kw.keyword}: {traffic}")

    #     return JsonResponse({
    #         "status": "true",
    #         "message": "Traffic updated for all keywords."
    #     })

    # except Exception as e:
    #     # ←—— Catches any error in the entire block above
    #     print(f"[Cron Error] {e}")
    #      return JsonResponse({"status": "true", "message": "Group processing completed"})
    
    
def get_traffic_monthly_avg(site_url, max_attempts=3):
    url = "https://ahrefs2.p.rapidapi.com/traffic"
    headers = {
        "x-rapidapi-key": RAPID_API_KEY,
        "x-rapidapi-host": "ahrefs2.p.rapidapi.com"
    }
    params = {"url": site_url, "mode": "exact"}

    for attempt in range(1, max_attempts + 1):
        try:
            resp = requests.get(url, headers=headers, params=params, timeout=60)
            resp.raise_for_status()
            return resp.json().get("trafficMonthlyAvg", 0)
        except requests.exceptions.RequestException as e:
            print(f"[Attempt {attempt}] {site_url} failed: {e}")
            time.sleep(2 * attempt)
        except ValueError as e:
            print(f"[Attempt {attempt}] Invalid JSON for {site_url}: {e}")
            break
    return 0

@api_view(["GET"])
@permission_classes([AllowAny])

def keywordTraffic(request):
    """
    Cron endpoint: fetches traffic for every keyword with a ranked_url
    in parallel threads, then updates the `traffic` field.
    """
    try:
        keywords = list(
            Keyword.objects
                   .exclude(ranked_url__isnull=True)
                   .exclude(ranked_url="")
        )

        updated_count = 0
        failed_ids = []

        with ThreadPoolExecutor(max_workers=TRAFFIC_THREAD_LIMIT) as executor:
            # Map each future to its keyword
            future_to_kw = {
                executor.submit(get_traffic_monthly_avg, kw.ranked_url): kw
                for kw in keywords
            }

            for future in as_completed(future_to_kw):
                kw = future_to_kw[future]
                try:
                    traffic = future.result()
                    Keyword.objects.filter(id=kw.id).update(traffic=traffic)
                    updated_count += 1
                    print(f"Updated {kw.keyword}: {traffic}")
                except Exception as e:
                    print(f"[Error] updating {kw.keyword} (ID {kw.id}): {e}")
                    failed_ids.append(kw.id)

        return JsonResponse({
            "status": "true",
            "message": "Traffic update completed",
            "updated": updated_count,
            "failed_ids": failed_ids
        })

    except Exception as e:
        # ←—— Catches any error in the entire block above
         print(f"[Cron Error] {e}")
         return JsonResponse({"status": "true", "message": "Group processing completed"})