"""INT-008 comparison boundaries. No live downloader or production integration."""
from contextlib import contextmanager
from datetime import datetime
from io import BytesIO
import ipaddress
from urllib.parse import urlsplit

MAX_IMAGE_BYTES = 16 * 1024 * 1024
MAX_BATCH_BYTES = 128 * 1024 * 1024
MAX_REDIRECTS = 2
REQUEST_SECONDS = 10.0
BATCH_SECONDS = 60.0


def frozen_opener(responses, *, allowed_hosts):
    """Validate captured response envelopes, then expose an offline opener.

    A future downloader must measure time/bytes itself and validate resolved IPs
    at every connection. These supplied timings are test inputs, not evidence
    of enforcement on a live socket. Response errors remain generator inputs.
    """
    allowed_hosts = frozenset(allowed_hosts)
    frozen = {}
    total_bytes = 0
    total_seconds = 0.0

    def safe(url):
        if not isinstance(url, str) or len(url) > 2048 or any(c.isspace() for c in url):
            raise ValueError('Unsafe media URL')
        parsed = urlsplit(url)
        if (parsed.scheme != 'https' or not parsed.hostname or parsed.hostname not in allowed_hosts
                or parsed.username is not None or parsed.password is not None
                or parsed.fragment or parsed.port not in (None, 443)
                or parsed.hostname == 'localhost' or parsed.hostname.endswith(('.local', '.localhost'))):
            raise ValueError('Unsafe media URL')
        try:
            ipaddress.ip_address(parsed.hostname)
        except ValueError:
            return
        raise ValueError('IP literal media URLs are forbidden')

    for url, response in responses.items():
        safe(url)
        if set(response) != {'body', 'status', 'seconds', 'redirects'}:
            raise ValueError('Invalid captured response')
        body, status, seconds, redirects = (response[k] for k in ('body', 'status', 'seconds', 'redirects'))
        if (not isinstance(body, bytes) or len(body) > MAX_IMAGE_BYTES or type(status) is not int
                or not 200 <= status <= 599 or 300 <= status < 400
                or type(seconds) not in (int, float) or not 0 <= seconds <= REQUEST_SECONDS
                or not isinstance(redirects, tuple) or len(redirects) > MAX_REDIRECTS):
            raise ValueError('Captured response exceeds policy')
        for target in redirects:
            safe(target)
        total_bytes += len(body)
        total_seconds += seconds
        if total_bytes > MAX_BATCH_BYTES or total_seconds > BATCH_SECONDS:
            raise ValueError('Captured batch exceeds policy')
        frozen[url] = (body, status)

    def open_response(request, timeout=None):
        url = request.full_url if hasattr(request, 'full_url') else str(request)
        safe(url)
        body, status = frozen.get(url, (b'', 404))
        if not 200 <= status < 300:
            raise OSError(f'Frozen HTTP status {status}')
        return BytesIO(body)

    return open_response


@contextmanager
def frozen_clock(monkeypatch):
    import datetime as dates
    import time
    from InvestmentManager.export_engine.portals.tabelaofert import renderer
    from InvestmentManager.export_engine.portals.gruntguru import renderer as guru_renderer
    class Clock(datetime):
        @classmethod
        def now(cls,tz=None):return cls(2026,10,27,12,0,0,tzinfo=tz)
        @classmethod
        def utcnow(cls):return cls(2026,10,27,12,0,0)
    with monkeypatch.context() as patch:
        patch.setattr(dates,'datetime',Clock)
        patch.setattr(time,'localtime',lambda *args:time.struct_time((2026,10,27,12,0,0,1,300,-1)))
        patch.setattr(renderer,'datetime',Clock)
        patch.setattr(guru_renderer,'datetime',Clock)
        yield
