"""Shared HTTP client for platform-data providers.

The only file (besides the provider modules that use it) that knows about
the backend used to fetch platform search suggestions and hashtag stats:
its base URL, auth, and retry behavior.
"""

import os
import time

import requests
from dotenv import load_dotenv

load_dotenv()

BASE_URL = "https://api.tikhub.io"
API_KEY = os.environ["TIKHUB_API_KEY"]
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

MAX_RETRIES = 4
RETRY_BACKOFF_SECONDS = 5.0
REQUEST_DELAY_SECONDS = 0.5
HTTP_OK = 200
HTTP_RATE_LIMITED = 429


def call_backend(path, params):
    """GET a backend endpoint with retries. Returns parsed JSON, or None on repeated failure."""
    url = f"{BASE_URL}{path}"
    delay = RETRY_BACKOFF_SECONDS
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            r = requests.get(url, headers=HEADERS, params=params, timeout=40)
        except requests.RequestException as e:
            print(f"  ⚠️ Network error on {path} (attempt {attempt}/{MAX_RETRIES}): {e}")
            time.sleep(delay)
            delay *= 2
            continue

        if r.status_code == HTTP_OK:
            return r.json()

        print(f"  ⚠️ {path} -> HTTP {r.status_code} (attempt {attempt}/{MAX_RETRIES}): {r.text[:200]}")
        if r.status_code == HTTP_RATE_LIMITED or 500 <= r.status_code < 600:
            time.sleep(delay)
            delay *= 2
            continue
        return None

    return None
