import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from dishhome_tool import DishHomeTool

# Credentials (In production, use environment variables)
USERNAME = "LBTWL-D57"
PASSWORD = "Dishhome@321"
API_KEY = "DISHHOME_SAFE_KEY_2026"

tool = DishHomeTool(username=USERNAME, password=PASSWORD)

@csrf_exempt
def check_connectivity(request):
    """Simple endpoint to check if the server can reach DishHome."""
    if request.headers.get("X-API-KEY") != API_KEY:
        return JsonResponse({"error": "Unauthorized"}, status=401)
    
    target_url = "https://care.dishhome.com.np/Account/Login"
    import requests
    import time
    start = time.time()
    try:
        response = requests.get(target_url, timeout=15)
        duration = time.time() - start
        return JsonResponse({
            "status": "success",
            "remote_status_code": response.status_code,
            "duration": f"{duration:.2f}s",
            "message": "Connected to DishHome"
        })
    except Exception as e:
        duration = time.time() - start
        return JsonResponse({
            "status": "error",
            "duration": f"{duration:.2f}s",
            "message": str(e)
        }, status=500)

@csrf_exempt
def fetch_bulk(request):
    if request.method != 'POST':
        return JsonResponse({"error": "Method not allowed. Use POST."}, status=405)

    # Check for API Key in headers
    request_key = request.headers.get("X-API-KEY")
    if request_key != API_KEY:
        return JsonResponse({"error": "Unauthorized: Invalid API Key"}, status=401)

    try:
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({"error": "Invalid JSON body."}, status=400)

    if not data or 'ids' not in data:
        return JsonResponse({"error": "No IDs provided in request body. Expected format: {'ids': [...]}"}, status=400)

    ids = data.get('ids', [])
    
    # Ensure logged in (DishHomeTool logic)
    success, msg = tool.login()
    if not success:
        return JsonResponse({"error": f"Login failed: {msg}"}, status=500)

    try:
        # Optimization: Fetch token once for the entire batch
        token = tool.get_verification_token()
        
        results = []
        from concurrent.futures import ThreadPoolExecutor, as_completed

        def fetch_worker(customer_id):
            customer_id = str(customer_id).strip()
            if not customer_id:
                return None
            detail = tool.get_customer_detail(customer_id, token=token)
            return {"id": customer_id, "data": detail}

        # Multi-threaded fetching (max 8 concurrent requests)
        with ThreadPoolExecutor(max_workers=8) as executor:
            future_to_id = {executor.submit(fetch_worker, cid): cid for cid in ids}
            for future in as_completed(future_to_id):
                res = future.result()
                if res:
                    results.append(res)
        
        return JsonResponse({
            "status": "success",
            "total": len(results),
            "results": results
        })
    except requests.exceptions.Timeout:
        return JsonResponse({"error": "Request to DishHome timed out. The portal might be slow or blocked."}, status=504)
    except Exception as e:
        return JsonResponse({"error": f"Internal Server Error: {str(e)}"}, status=500)
