import logging
import os
import warnings
from pathlib import Path

import requests
from tenacity import (
    retry,
    retry_if_exception_type,
    stop_after_attempt,
    wait_fixed,
)

from teklia_toolbox import VERSION

logger = logging.getLogger(__name__)


def get_arkindex_client(**options):
    warnings.warn(
        "get_arkindex_client() is deprecated and should be replaced with a direct call to ArkindexClient(**options_from_env()).",
        DeprecationWarning,
        stacklevel=2,
    )
    from arkindex import ArkindexClient

    return ArkindexClient(**options)


# Time to wait before retrying the IIIF image information fetching
HTTP_GET_RETRY_BACKOFF = 10

# Specific User-Agent to bypass potential server limitations
USER_AGENT = os.getenv("REQUESTS_USER_AGENT", f"Teklia/Tools {VERSION}")

DOWNLOAD_CHUNK_SIZE = 8192


@retry(
    reraise=True,
    retry=retry_if_exception_type(requests.RequestException),
    stop=stop_after_attempt(3),
    wait=wait_fixed(HTTP_GET_RETRY_BACKOFF),
)
def download_file(url: str, path: Path) -> None:
    """
    Download a URL into a local path, retrying if necessary
    """
    # Only auto-detect whether to use SSL verification when the Arkindex client is available
    try:
        from arkindex import should_verify_cert

        verify = should_verify_cert(url)
    except ImportError:
        verify = False

    with requests.get(
        url,
        stream=True,
        headers={"User-Agent": USER_AGENT},
        verify=verify,
    ) as r:
        r.raise_for_status()
        with path.open("wb") as f:
            for chunk in r.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE):
                if chunk:  # Ignore empty chunks
                    f.write(chunk)
