"""Offline resource boundary; decoding/conversion remains in copied modules."""
from io import BytesIO
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import url2pathname

from . import runtime_paths


class NetworkDisabledError(RuntimeError):
    pass


def read_file_bytes(path):
    return runtime_paths.checked_path(path).read_bytes()


def urlopen(request, timeout=None):
    """Compatible subset used by the copy: fixture bytes or a local file URL.

    No socket/HTTP/FTP implementation is present. Fixture dictionaries can use
    their original HTTPS URLs while their exact response bytes are supplied.
    """
    url = request.full_url if hasattr(request, "full_url") else str(request)
    supplied = runtime_paths.current().url_responses
    if url in supplied:
        return BytesIO(supplied[url])
    parts = urlsplit(url)
    if parts.scheme == "file" and parts.netloc in ("", "localhost"):
        return BytesIO(read_file_bytes(Path(url2pathname(parts.path))))
    raise NetworkDisabledError("Live network resource access is disabled; supply fixture response bytes")
