# Path: mapchete/io/_path.py
# def fs_from_path(path, timeout=5, session=None, username=None, password=None, **kwargs):
#     """Guess fsspec FileSystem from path and initialize using the desired options."""
#     if path.startswith("s3://"):
#         return fsspec.filesystem(
#             "s3",
#             requester_pays=os.environ.get("AWS_REQUEST_PAYER") == "requester",
#             config_kwargs=dict(connect_timeout=timeout, read_timeout=timeout),
#             session=session,
#             client_kwargs=kwargs,
#         )
#     elif path.startswith(("http://", "https://")):
#         if username:  # pragma: no cover
#             from aiohttp import BasicAuth
# 
#             auth = BasicAuth(username, password)
#         else:
#             auth = None
#         return fsspec.filesystem("https", auth=auth, asynchronous=False, **kwargs)
#     else:
#         return fsspec.filesystem("file", asynchronous=False, **kwargs)
# 
# def path_exists(path, fs=None, **kwargs):
#     """
#     Check if file exists either remote or local.
# 
#     Parameters
#     ----------
#     path : path to file
# 
#     Returns
#     -------
#     exists : bool
#     """
#     fs = fs or fs_from_path(path, **kwargs)
#     fs.invalidate_cache(path=path)
#     return fs.exists(path)
# 
# Path: mapchete/io/_misc.py
# def get_boto3_bucket(bucket_name):
#     """Return boto3.Bucket object from bucket name."""
#     import boto3
# 
#     url = os.environ.get("AWS_S3_ENDPOINT")
#     return boto3.resource(
#         "s3",
#         endpoint_url=(
#             "https://" + url
#             if url and not url.startswith(("http://", "https://"))
#             else url
#         ),
#     ).Bucket(bucket_name)


import fsspec
import json
import logging
import os
from mapchete.io._path import fs_from_path, path_exists
from mapchete.io._misc import get_boto3_bucket



logger = logging.getLogger(__name__)


def write_json(path, params, fs=None, **kwargs):
    """Write local or remote."""
    logger.debug(f"write {params} to {path}")
    fs = fs or fs_from_path(path, **kwargs)
    # using python 3.7 or higher we can use the fs.mkdir() call
    fs.mkdirs(os.path.dirname(path), exist_ok=True)
    with fs.open(path, "w") as dst:
        json.dump(params, dst, sort_keys=True, indent=4)


def read_json(path, fs=None, **kwargs):
    """Read local or remote."""
    fs = fs or fs_from_path(path, **kwargs)
    try:
        with fs.open(path) as src:
            return json.loads(src.read())
    except Exception as e:

# Path: mapchete/io/_path.py
# def fs_from_path(path, timeout=5, session=None, username=None, password=None, **kwargs):
#     """Guess fsspec FileSystem from path and initialize using the desired options."""
#     if path.startswith("s3://"):
#         return fsspec.filesystem(
#             "s3",
#             requester_pays=os.environ.get("AWS_REQUEST_PAYER") == "requester",
#             config_kwargs=dict(connect_timeout=timeout, read_timeout=timeout),
#             session=session,
#             client_kwargs=kwargs,
#         )
#     elif path.startswith(("http://", "https://")):
#         if username:  # pragma: no cover
#             from aiohttp import BasicAuth
# 
#             auth = BasicAuth(username, password)
#         else:
#             auth = None
#         return fsspec.filesystem("https", auth=auth, asynchronous=False, **kwargs)
#     else:
#         return fsspec.filesystem("file", asynchronous=False, **kwargs)
# 
# def path_exists(path, fs=None, **kwargs):
#     """
#     Check if file exists either remote or local.
# 
#     Parameters
#     ----------
#     path : path to file
# 
#     Returns
#     -------
#     exists : bool
#     """
#     fs = fs or fs_from_path(path, **kwargs)
#     fs.invalidate_cache(path=path)
#     return fs.exists(path)
# 
# Path: mapchete/io/_misc.py
# def get_boto3_bucket(bucket_name):
#     """Return boto3.Bucket object from bucket name."""
#     import boto3
# 
#     url = os.environ.get("AWS_S3_ENDPOINT")
#     return boto3.resource(
#         "s3",
#         endpoint_url=(
#             "https://" + url
#             if url and not url.startswith(("http://", "https://"))
#             else url
#         ),
#     ).Bucket(bucket_name)


# Path: mapchete/io/_json.py
import fsspec
import json
import logging
import os
from mapchete.io._path import fs_from_path, path_exists
from mapchete.io._misc import get_boto3_bucket




logger = logging.getLogger(__name__)


def write_json(path, params, fs=None, **kwargs):
    """Write local or remote."""
    logger.debug(f"write {params} to {path}")
    fs = fs or fs_from_path(path, **kwargs)
    # using python 3.7 or higher we can use the fs.mkdir() call
    fs.mkdirs(os.path.dirname(path), exist_ok=True)
    with fs.open(path, "w") as dst:
        json.dump(params, dst, sort_keys=True, indent=4)


def read_json(path, fs=None, **kwargs):
    """Read local or remote."""
    fs = fs or fs_from_path(path, **kwargs)
    try:
        with fs.open(path) as src:
            return json.loads(src.read())
    except Exception as e:

        if path_exists(path, fs=fs):  # pragma: no cover