"""Bounded, public dictionary inputs for the unchanged offline engine."""
import hashlib
from threading import RLock
import time
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
import xml.etree.ElementTree as ET
from . import domestic_batch_limits as limits
from . import export_performance as performance

BASE = 'https://eksporty.domiporta.pl/Spec'
URLS = (f'{BASE}/GetCategoryDictionary',) + tuple(
    f'{BASE}/GetFeatureDictionary?type={kind}'
    for kind in ('typbudynku', 'kanalizacja', 'rodzajdzialki', 'przeznaczenieallads', 'media')
)
_cache = {}
_lock = RLock()
MAX_BYTES = 2 * 1024 * 1024


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


def _download(url):
    # No caller-controlled destinations, proxies, cookies or credentials.
    if url not in URLS:
        raise ValueError('Unsupported dictionary URL')
    opener = build_opener(ProxyHandler({}), _NoRedirect())
    limits.check('dictionary_open')
    timeout = limits.network_timeout() if limits.current() is not None else 15
    try:
        with opener.open(Request(url, headers={'Accept': 'application/xml'}), timeout=timeout) as response:
            if response.status != 200:
                raise ValueError('Dictionary HTTP status')
            if limits.current() is None:
                body = response.read(MAX_BYTES + 1)
            else:
                chunks, size = [], 0
                while size <= MAX_BYTES:
                    limits.check('dictionary_read')
                    # CPython HTTPResponse exposes its socket through BufferedReader.
                    # Refresh the socket's idle timeout before each bounded read.
                    sock = getattr(getattr(getattr(response, 'fp', None), 'raw', None), '_sock', None)
                    if sock is not None:
                        sock.settimeout(limits.network_timeout())
                    read = getattr(response, 'read1', response.read)
                    chunk = read(min(65536, MAX_BYTES + 1 - size))
                    limits.check('dictionary_read')
                    if not chunk:
                        break
                    chunks.append(chunk); size += len(chunk)
                body = b''.join(chunks)
    except Exception as exc:
        if limits.current() is not None and (isinstance(exc, TimeoutError) or isinstance(getattr(exc, 'reason', None), TimeoutError)):
            raise limits.BatchStop('network_timeout', 'dictionary_network') from exc
        raise
    limits.check('dictionary_parse')
    if not body or len(body) > MAX_BYTES or b'<!DOCTYPE' in body.upper():
        raise ValueError('Invalid dictionary body')
    root = ET.fromstring(body)
    if not any(node.attrib.get('id') for node in root):
        raise ValueError('Dictionary has no records')
    limits.check('dictionary_parse')
    return body


@performance.measured('dictionary_refresh')
def dictionary_inputs(portal):
    """Return exact response bytes and explicit success/fallback diagnostics.

    Failed responses are omitted, so the engine retains its original fallback.
    An expired successful response is never presented as a fresh fetch.
    """
    if portal != 'domiporta':
        return {}, []
    responses, context = {}, []
    with performance.lock_context(limits.locked(_lock), 'dictionary_lock'):
        for url in URLS:
            limits.check('dictionary_lookup')
            cached = _cache.get(url)
            if cached is None or time.monotonic() >= cached[0]:
                try:
                    body = _download(url)
                    limits.check('dictionary_download')
                    diagnostic = {'url': url, 'status': 'available',
                                  'sha256': hashlib.sha256(body).hexdigest(), 'size': len(body)}
                    ttl = 21600
                except Exception as exc:
                    if limits.current() is not None and (isinstance(exc, TimeoutError) or isinstance(getattr(exc, 'reason', None), TimeoutError)):
                        raise limits.BatchStop('network_timeout', 'dictionary_network') from exc
                    body = None
                    diagnostic = {'url': url, 'status': 'unavailable_fallback'}
                    ttl = 300
                cached = (time.monotonic() + ttl, body, diagnostic)
                _cache[url] = cached
            if cached[1] is not None:
                responses[url] = cached[1]
            context.append(dict(cached[2]))
    return responses, context


def cached_dictionary_context(portal):
    """Read existing fresh cache only; never perform HTTP during listing/checks."""
    if portal != 'domiporta':
        return []
    with performance.lock_context(limits.locked(_lock), 'dictionary_lock'):
        now = time.monotonic()
        entries = [_cache.get(url) for url in URLS]
        if any(item is None or now >= item[0] or item[1] is None for item in entries):
            return None
        return [dict(item[2]) for item in entries]
