"""Bounded HTTPS capture. Explicit public IP pins remove live DNS/rebinding.

Pins are trusted server configuration, never form inputs. No proxy, resolver,
background worker or implicit host discovery. Missing pins fail closed.
"""
import hashlib
import http.client
import io
import ipaddress
import json
import os
import socket
import ssl
import time
from urllib.parse import urljoin, urlsplit
import warnings

from PIL import Image

MAX_IMAGE = 16 * 1024 * 1024
MAX_BATCH = 128 * 1024 * 1024
MAX_PIXELS = 20_000_000
MAX_EDGE = 16384
REQUEST_SECONDS = 10.0
BATCH_SECONDS = 60.0
MAX_REDIRECTS = 2
RASTER_FORMATS = {'JPEG','PNG','WEBP','GIF'}
SPECIAL_V4 = tuple(ipaddress.ip_network(net) for net in (
    '0.0.0.0/8','10.0.0.0/8','100.64.0.0/10','127.0.0.0/8','169.254.0.0/16',
    '172.16.0.0/12','192.0.0.0/24','192.0.2.0/24','192.88.99.0/24','192.168.0.0/16',
    '198.18.0.0/15','198.51.100.0/24','203.0.113.0/24','224.0.0.0/4','240.0.0.0/4'))


class MediaError(ValueError):
    pass


def configured_pins(settings=None):
    value=(settings or {}).get('FOREIGN_MEDIA_HOST_PINS')
    if value is None:
        try:value=json.loads(os.environ.get('FOREIGN_MEDIA_HOST_PINS','{}'))
        except ValueError as exc:raise MediaError('invalid_pin_configuration') from exc
    if not isinstance(value,dict):raise MediaError('invalid_pin_configuration')
    return value


def _remaining(deadline):
    remaining = deadline - time.monotonic()
    if remaining <= 0: raise TimeoutError('Media deadline')
    return remaining


def _target(url, pins):
    if not isinstance(url, str) or len(url) > 2048 or any(ord(c) <= 32 or ord(c) == 127 for c in url):
        raise MediaError('unsafe_url')
    parts = urlsplit(url)
    host = parts.hostname
    if (parts.scheme != 'https' or not host or host.endswith('.')
            or parts.port not in (None, 443) or parts.username is not None
            or parts.password is not None or parts.fragment
            or host == 'localhost' or host.endswith(('.local', '.localhost'))):
        raise MediaError('unsafe_url')
    try: ipaddress.ip_address(host)
    except ValueError: pass
    else: raise MediaError('ip_literal')
    approved = pins.get(host) if isinstance(pins, dict) else None
    if not isinstance(approved, (list, tuple)) or not approved:
        raise MediaError('host_not_pinned')
    addresses = []
    for value in approved:
        try: address = ipaddress.ip_address(value)
        except ValueError as exc: raise MediaError('invalid_pin') from exc
        if (not address.is_global or address.is_multicast or address.is_reserved
                or address.version==4 and any(address in net for net in SPECIAL_V4)
                or address.version==6 and (address.ipv4_mapped is not None
                    or address.sixtofour is not None or address.teredo is not None)):
            raise MediaError('non_public_pin')
        addresses.append(address)
    return parts, addresses[0]


class _DeadlineRaw(io.RawIOBase):
    def __init__(self, owner, deadline):
        self.owner, self.deadline = owner, deadline
    def readable(self): return True
    def readinto(self, buffer):
        self.owner.sock.settimeout(_remaining(self.deadline))
        return self.owner.sock.recv_into(buffer)
    def close(self):
        if not self.closed:
            try: self.owner._reader_closed()
            finally: super().close()


class _DeadlineSocket:
    def __init__(self, sock, deadline):
        self.sock, self.deadline = sock, deadline
        self._readers, self._closing = 0, False
    def sendall(self, data):
        self.sock.settimeout(_remaining(self.deadline))
        return self.sock.sendall(data)
    def makefile(self, mode, *args, **kwargs):
        if mode != 'rb': raise MediaError('unsupported_stream')
        self._readers += 1
        return io.BufferedReader(_DeadlineRaw(self, self.deadline))
    def _reader_closed(self):
        self._readers -= 1
        if self._closing and not self._readers: self.sock.close()
    def close(self):
        self._closing = True
        if not self._readers: self.sock.close()


class PinnedHTTPSConnection(http.client.HTTPSConnection):
    def __init__(self, host, address, deadline):
        context = ssl.create_default_context()
        super().__init__(host, port=443, timeout=_remaining(deadline), context=context)
        self.address, self.deadline = address, deadline

    def connect(self):
        # Numeric sockaddr, never socket.create_connection/getaddrinfo(host).
        family = socket.AF_INET6 if self.address.version == 6 else socket.AF_INET
        raw = socket.socket(family, socket.SOCK_STREAM)
        try:
            raw.settimeout(_remaining(self.deadline))
            endpoint = (str(self.address), 443, 0, 0) if family == socket.AF_INET6 else (str(self.address), 443)
            raw.connect(endpoint)
            raw.settimeout(_remaining(self.deadline))
            tls = self._context.wrap_socket(raw, server_hostname=self.host)
            self.sock = _DeadlineSocket(tls, self.deadline)
        except BaseException:
            raw.close()
            raise


def _capture_one(url, pins, deadline, connection_factory, budget):
    current = url
    for hop in range(MAX_REDIRECTS + 1):
        parts, address = _target(current, pins)
        connection = connection_factory(parts.hostname, address, deadline)
        response=None
        try:
            path = (parts.path or '/') + ('?' + parts.query if parts.query else '')
            connection.request('GET', path, headers={'Host': parts.hostname,
                'User-Agent': 'InvestmentManager/1.0', 'Accept-Encoding': 'identity'})
            response = connection.getresponse()
            if response.status in (301, 302, 303, 307, 308):
                location = response.getheader('Location')
                if not location or hop == MAX_REDIRECTS: raise MediaError('redirect_limit')
                current = urljoin(current, location)
                continue
            if not 200 <= response.status < 300:
                return None, {'status': 'http_error', 'http_status': response.status,
                              'sha256': None, 'size': 0, 'error': 'http_error'}
            if response.getheader('Content-Encoding', 'identity').lower() != 'identity':
                raise MediaError('encoded_response')
            chunks, size = [], 0
            while True:
                _remaining(deadline)
                chunk = response.read1(min(65536, MAX_IMAGE + 1 - size))
                if not chunk: break
                size += len(chunk)
                budget[0] += len(chunk)
                if budget[0] > MAX_BATCH: raise MediaError('batch_size')
                if size > MAX_IMAGE: raise MediaError('image_size')
                chunks.append(chunk)
            body = b''.join(chunks)
            with warnings.catch_warnings():
                warnings.simplefilter('error', Image.DecompressionBombWarning)
                with Image.open(io.BytesIO(body)) as image:
                    if (image.width <= 0 or image.height <= 0 or max(image.size) > MAX_EDGE
                            or image.width * image.height > MAX_PIXELS):
                        raise MediaError('image_dimensions')
                    if image.format not in RASTER_FORMATS:raise MediaError('image_format')
                    image.verify()
                # Verify() alone does not decode JPEG pixel data. Force only the
                # first bounded raster frame, without changing the input bytes.
                with Image.open(io.BytesIO(body)) as image:image.load()
            _remaining(deadline)
            return body, {'status': 'available', 'http_status': response.status,
                          'sha256': hashlib.sha256(body).hexdigest(), 'size': size, 'error': None}
        finally:
            try:
                if response is not None:response.close()
            finally:connection.close()
    raise MediaError('redirect_limit')


def capture(urls, pins, *, connection_factory=None):
    """One frozen result per exact URL. Errors also participate in fingerprint."""
    factory = connection_factory or PinnedHTTPSConnection
    responses, outcomes, budget = {}, {}, [0]
    deadline = time.monotonic() + BATCH_SECONDS
    for url in dict.fromkeys(urls):
        _remaining(deadline)
        try:
            body, outcome = _capture_one(url, pins,
                min(deadline, time.monotonic() + REQUEST_SECONDS), factory, budget)
        except MediaError as exc:
            if str(exc) == 'batch_size': raise
            body, outcome = None, {'status': 'blocked', 'http_status': None, 'sha256': None,
                                   'size': 0, 'error': str(exc)}
        except AssertionError:
            raise  # audit/test network violations must never be hidden
        except Exception:
            body, outcome = None, {'status': 'unavailable', 'http_status': None,
                                   'sha256': None, 'size': 0, 'error': 'capture_failed'}
        if body is not None:
            responses[url] = body
        outcomes[url] = outcome
    _remaining(deadline)
    return responses, outcomes
