"""DataNavoAPI local SDK: simulated execution and explicit live reads; standard library, no retries."""
import copy
import datetime
import http.client
import json
import math
import re
import socket
import threading
import time
import urllib.parse

_MAX_BYTES = 1024 * 1024
_MESSAGES = {
    'invalid_config': '请检查本机端口、与客户端模式匹配的客户 Key 和超时配置。',
    'live_read_only': '此客户端只读取已保存的真实调用记录；不执行、报价或创建任务。',
    'invalid_params': '请检查能力、参数、模拟场景与幂等编号。',
    'invalid_catalog': '本地能力目录无效，未发起执行。',
    'capability_not_found': '能力不存在，请先读取目录。',
    'local_transport_error': '本地请求未能完成。若结果未知，请保留原参数和幂等编号，手动查询原请求。',
    'response_too_large': '本地响应超过 1 MB。',
    'invalid_response': '本地响应不符合客户端协议。',
}


class GuanliuError(Exception):
    def __init__(self, code, outcome_unknown=False):
        self.code = code if code in _MESSAGES else 'invalid_response'
        self.outcome_unknown = outcome_unknown is True
        super().__init__(_MESSAGES[self.code])


def _fail(code, unknown=False):
    raise GuanliuError(code, unknown)


def _catalog_valid(data):
    if not isinstance(data, dict) or not isinstance(data.get('capabilities'), list) or len(data['capabilities']) > 1000:
        return False
    ids = set()
    for cap in data['capabilities']:
        if not isinstance(cap, dict):
            return False
        identity = cap.get('id')
        if not isinstance(identity, str) or not re.fullmatch(r'[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){1,7}', identity) or identity in ids or cap.get('method') != 'GET' or cap.get('path') != '/v1/' + identity.replace('.', '/') or not isinstance(cap.get('parameters'), list) or len(cap['parameters']) > 32:
            return False
        ids.add(identity)
        names = set()
        for param in cap['parameters']:
            if not isinstance(param, dict):
                return False
            name = param.get('name')
            if not isinstance(name, str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,63}', name) or name in names or name in ('mode', 'api_key', 'authorization', 'headers', 'base_url'):
                return False
            names.add(name)
    return True


def _simulation(body):
    meta = body.get('meta')
    if not isinstance(meta, dict):
        return False
    billing = meta.get('billing')
    return meta.get('mode') == 'simulated' and meta.get('provider') == 'mock' and isinstance(billing, dict) and billing.get('charged') is False and billing.get('currency') == 'TEST_CREDIT' and billing.get('amount') == '0'


def _integer(value, minimum=0, maximum=9007199254740991):
    return type(value) is int and minimum <= value <= maximum


def _timestamp(value):
    if not isinstance(value, str) or not value.endswith('Z'):
        return False
    try:
        datetime.datetime.fromisoformat(value[:-1] + '+00:00')
        return True
    except ValueError:
        return False


def _identity(value):
    return isinstance(value, str) and re.fullmatch(r'[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}', value, re.I) is not None


def _capability_id(value):
    return isinstance(value, str) and len(value) <= 200 and re.fullmatch(r'[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){1,7}', value) is not None


def _calendar_date(value):
    if not isinstance(value, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', value):
        return False
    try:
        return datetime.date.fromisoformat(value).isoformat() == value
    except ValueError:
        return False


def _readonly_meta(meta):
    return isinstance(meta, dict) and meta.get('mode') == 'simulated' and meta.get('provider') == 'none' and meta.get('environment') == 'local_sandbox' and meta.get('readOnly') is True and type(meta.get('reservedCredits')) is int and meta['reservedCredits'] == 0 and type(meta.get('creditsDebited')) is int and meta['creditsDebited'] == 0 and meta.get('realMoneyCharged') is False


def _usage_filters(value):
    if type(value) is not dict or any(key not in ('status', 'capability', 'from', 'to', 'page', 'pageSize') for key in value):
        _fail('invalid_params')
    value = value.copy()
    for key, item in value.items():
        valid = (item in ('all', 'success', 'failure') if key == 'status' else (item == '' or _capability_id(item)) if key == 'capability' else _calendar_date(item) if key in ('from', 'to') else _integer(item, 1, 1000000) if key == 'page' else type(item) is int and item in (20, 50, 100))
        if not valid:
            _fail('invalid_params')
    if value.get('from') and value.get('to') and value['from'] > value['to']:
        _fail('invalid_params')
    return {'status': value.get('status', 'all'), 'capability': value.get('capability', ''), 'from': value.get('from'), 'to': value.get('to'), 'page': value.get('page', 1), 'pageSize': value.get('pageSize', 20)}


def _valid_account(data):
    if not isinstance(data, dict) or data.get('scope') != 'current_key' or data.get('timezone') != 'UTC' or data.get('currency') != 'TEST_CREDIT' or not _timestamp(data.get('asOf')):
        return False
    key, wallet, budget, daily = data.get('key'), data.get('wallet'), data.get('budget'), data.get('dailyRequests')
    if not isinstance(key, dict) or not _identity(key.get('id')) or not isinstance(key.get('name'), str) or not isinstance(key.get('prefix'), str) or not re.fullmatch(r'gl_test_[A-Za-z0-9_-]{8}', key['prefix']) or not isinstance(key.get('capabilities'), list) or not all(_capability_id(item) for item in key['capabilities']) or not _integer(key.get('dailyLimitRequests'), 1, 10000) or not _timestamp(key.get('createdAt')) or not _timestamp(key.get('expiresAt')) or not ('lastUsedAt' in key and (key['lastUsedAt'] is None or _timestamp(key['lastUsedAt']))):
        return False
    if not isinstance(wallet, dict) or not all(_integer(wallet.get(name)) for name in ('balanceCredits', 'reservedCredits', 'availableCredits')) or not isinstance(daily, dict) or not all(_integer(daily.get(name)) for name in ('used', 'reserved', 'limit', 'remaining')):
        return False
    if not isinstance(budget, dict) or budget.get('currency') != 'TEST_CREDIT' or budget.get('timezone') != 'UTC' or not _identity(budget.get('groupId')) or not _timestamp(budget.get('asOf')):
        return False
    for name in ('daily', 'monthly', 'total'):
        window = budget.get(name)
        if not isinstance(window, dict) or any(field not in window for field in ('limitCredits', 'spentCredits', 'reservedCredits', 'remainingCredits', 'startsAt', 'endsAt')) or not (window['limitCredits'] is None or _integer(window['limitCredits'], 1, 1000000)) or not _integer(window['spentCredits']) or not _integer(window['reservedCredits']) or not (window['remainingCredits'] is None or _integer(window['remainingCredits'])) or not (window['startsAt'] is None or _timestamp(window['startsAt'])) or not (window['endsAt'] is None or _timestamp(window['endsAt'])):
            return False
    return True


def _valid_usage(data, query):
    if not isinstance(data, dict) or data.get('scope') != 'current_key' or not _identity(data.get('keyId')) or data.get('timezone') != 'UTC' or data.get('currency') != 'TEST_CREDIT' or not _timestamp(data.get('asOf')) or not isinstance(data.get('filters'), dict) or any(name not in data['filters'] or data['filters'][name] != query[name] for name in ('status', 'capability', 'from', 'to')):
        return False
    if type(data.get('page')) is not int or type(data.get('pageSize')) is not int or data['page'] != query['page'] or data['pageSize'] != query['pageSize'] or not _integer(data.get('total')) or type(data.get('pages')) is not int or data['pages'] != max(1, math.ceil(data['total'] / query['pageSize'])) or not isinstance(data.get('items'), list) or len(data['items']) > query['pageSize'] or not isinstance(data.get('summary'), dict):
        return False
    summary = data['summary']
    if not all(_integer(summary.get(name)) for name in ('requests', 'successes', 'failures', 'spentCredits')) or summary['requests'] != data['total'] or summary['successes'] + summary['failures'] != data['total']:
        return False
    return all(isinstance(row, dict) and _identity(row.get('id')) and _identity(row.get('requestId')) and _capability_id(row.get('capability')) and _integer(row.get('httpStatus'), 100, 599) and _integer(row.get('costCredits')) and _timestamp(row.get('createdAt')) for row in data['items'])


_CALL_STATES = ('pending', 'succeeded', 'failed', 'timed_out', 'interrupted')


def _calls_filters(value):
    if type(value) is not dict or any(k not in ('state', 'capability', 'from', 'to', 'page', 'pageSize') for k in value) or ('state' in value and value['state'] not in ('all',) + _CALL_STATES):
        _fail('invalid_params')
    query = _usage_filters({k: v for k, v in value.items() if k != 'state'})
    del query['status']
    return dict(state=value.get('state', 'all'), **query)


def _call_base(data):
    return isinstance(data, dict) and data.get('scope') == 'current_key' and _identity(data.get('keyId')) and data.get('timezone') == 'UTC' and data.get('currency') == 'TEST_CREDIT' and _timestamp(data.get('asOf'))


def _valid_call(row, key_id):
    if not isinstance(row, dict) or not _identity(row.get('requestId')) or row.get('keyId') != key_id or not _capability_id(row.get('capability')) or row.get('state') not in _CALL_STATES or row.get('scenario') not in ('success', 'failure', 'timeout') or not all(_timestamp(row.get(k)) for k in ('createdAt', 'deadlineAt', 'leaseExpiryAt')) or not all(_integer(row.get(k)) for k in ('chargedCredits', 'reservedCredits', 'releasedCredits')) or type(row.get('leaseExpired')) is not bool:
        return False
    if row['state'] == 'pending':
        return 'completedAt' in row and row['completedAt'] is None and 'httpStatus' in row and row['httpStatus'] is None and row.get('resultAvailable') is False and row['chargedCredits'] == 0 and row['releasedCredits'] == 0 and (not row['leaseExpired'] or row['reservedCredits'] == 0)
    return _timestamp(row.get('completedAt')) and _integer(row.get('httpStatus'), 200, 599) and type(row.get('resultAvailable')) is bool and row['reservedCredits'] == 0 and (row['httpStatus'] == 200 and row['releasedCredits'] == 0 if row['state'] == 'succeeded' else row['httpStatus'] >= 400 and row['chargedCredits'] == 0)


def _valid_calls(data, query):
    if not _call_base(data) or not isinstance(data.get('filters'), dict) or any(data['filters'].get(k) != query[k] for k in ('state', 'capability', 'from', 'to')) or not _integer(data.get('page'), 1) or data['page'] != query['page'] or not _integer(data.get('pageSize')) or data['pageSize'] != query['pageSize'] or not _integer(data.get('total')) or not _integer(data.get('pages'), 1) or data['pages'] != max(1, math.ceil(data['total'] / query['pageSize'])) or not isinstance(data.get('items'), list) or len(data['items']) > query['pageSize'] or not isinstance(data.get('summary'), dict):
        return False
    summary = data['summary']
    return all(_integer(summary.get(k)) for k in ('requests', 'pending', 'succeeded', 'failed', 'timedOut', 'interrupted', 'chargedCredits', 'reservedCredits', 'releasedCredits')) and summary['requests'] == data['total'] and sum(summary[k] for k in ('pending', 'succeeded', 'failed', 'timedOut', 'interrupted')) == data['total'] and all(_valid_call(row, data['keyId']) for row in data['items'])


def _valid_receipt(data, request_id, result=False):
    if not _call_base(data) or not _valid_call(data.get('call'), data['keyId']) or data['call']['requestId'] != request_id:
        return False
    if not result:
        return True
    response = data.get('response')
    if not isinstance(response, dict) or not _integer(response.get('status'), 200, 599) or response['status'] != data['call']['httpStatus'] or not isinstance(response.get('body'), dict):
        return False
    body = response['body']
    return data['call']['resultAvailable'] and body.get('request_id') == request_id and _simulation(body) and body['meta'].get('replayed') is True and type(body['meta']['billing'].get('credits_debited')) is int and body['meta']['billing']['credits_debited'] == 0 and body['meta']['billing'].get('original_credits_debited') == data['call']['chargedCredits'] and isinstance(body['meta'].get('execution'), dict) and body['meta']['execution'].get('state') == data['call']['state']


def _read_response(response, validate):
    status, body = response['status'], response['body']
    code = body.get('code')
    if not isinstance(code, str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,99}', code) or ('meta' in body and not _readonly_meta(body['meta'])):
        _fail('invalid_response')
    if status < 400 and (status != 200 or code != 'ok' or not _readonly_meta(body.get('meta')) or not validate(body.get('data'))):
        _fail('invalid_response')
    return response


_POST_PATHS={'/v1/douyin/index/keywords/history','/v1/douyin/users/history','/v1/x/users/get','/v1/douyin/xingtu/creators/get'}

def _parameter_value(value):
    if isinstance(value,str) or type(value) is bool:
        return True
    if type(value) in (int,float):
        try:
            return math.isfinite(value)
        except OverflowError:
            return False
    return isinstance(value,list) and len(value)<=100 and all(isinstance(item,str) for item in value)

def _projection_query(view,fields):
    values={}
    if view is not None:
        if view not in ('compact','standard','full'):
            _fail('invalid_params')
        values['view']=view
    if fields is not None:
        parts=[x.strip() for x in fields.split(',')] if isinstance(fields,str) else fields
        if not isinstance(parts,list) or not 1<=len(parts)<=64 or any(not isinstance(x,str) or len(x)>128 or len(x.split('.'))>8 or any(not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',p) or p in ('__proto__','constructor','prototype') for p in x.split('.')) for x in parts) or len(set(parts))!=len(parts):
            _fail('invalid_params')
        values['fields']=','.join(parts)
    return urllib.parse.urlencode(values)

def _amount_micros(value):
    if not isinstance(value,str) or not re.fullmatch(r'(?:0|[1-9]\d{0,6})(?:\.\d{1,6})?',value):
        return -1
    parts=value.split('.')
    return int(parts[0])*1000000+int((parts[1] if len(parts)>1 else '').ljust(6,'0'))

def _run_input(value):
    if type(value) is not dict or set(value)-{'task_id','task_revision','max_amount','max_calls','ttl_seconds'} or not all(isinstance(value.get(k),str) and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:-]{0,99}',value[k]) and 'gl_test_' not in value[k] for k in ('task_id','task_revision')) or not _integer(value.get('max_calls'),1,10000) or not 1<=_amount_micros(value.get('max_amount'))<=10**12 or ('ttl_seconds' in value and not _integer(value['ttl_seconds'],60,86400)):
        _fail('invalid_params')
    return value.copy()

def _valid_run(data,run_id):
    if not isinstance(data,dict) or data.get('scope')!='current_key' or data.get('currency')!='TEST_CREDIT' or data.get('run_id')!=run_id or not _identity(data.get('key_id')) or not all(_timestamp(data.get(k)) for k in ('created_at','expires_at','read_at')) or type(data.get('expired')) is not bool or not _integer(data.get('max_calls'),1,10000) or not _integer(data.get('calls_used'),0,data['max_calls']) or data.get('remaining_calls')!=data['max_calls']-data['calls_used']:
        return False
    maximum,settled,held,left=[_amount_micros(data.get(k)) for k in ('max_amount','settled','held','remaining_amount')]
    return all(0<=x<=10**12 for x in (maximum,settled,held,left)) and maximum>0 and left==maximum-settled-held and isinstance(data.get('task_id'),str) and isinstance(data.get('task_revision'),str)

def _valid_standing(data,key):
    return isinstance(data,dict) and data.get('scope')=='current_key' and data.get('currency')=='TEST_CREDIT' and data.get('idempotency_key')==key and data.get('state') in ('free','in_progress','settled','failed') and (data.get('request_id') is None or _identity(data.get('request_id'))) and (data.get('capability') is None or _capability_id(data.get('capability'))) and (data.get('charged') is None or 0<=_amount_micros(data['charged'])<=10**12) and (data.get('result_status') is None or _integer(data['result_status'],100,599)) and (data.get('error_code') is None or isinstance(data['error_code'],str)) and data.get('result_expires_at') is None and type(data.get('lease_expired')) is bool


class GuanliuClient:
    # No __dict__, credential repr, implicit environment access or pickling.
    __slots__ = ('__key', '__port', '__timeout', '__cached', '__cached_at')

    def __init__(self, api_key, port=4321, timeout_ms=5000):
        if not isinstance(api_key, str) or not re.fullmatch(r'gl_test_[A-Za-z0-9_-]{43}', api_key) or isinstance(port, bool) or not re.fullmatch(r'[0-9]{1,5}', str(port)) or not 1 <= int(port) <= 65535 or type(timeout_ms) is not int or not 1 <= timeout_ms <= 60000:
            _fail('invalid_config')
        self.__key = api_key
        self.__port = int(port)
        self.__timeout = timeout_ms / 1000
        self.__cached = None
        self.__cached_at = 0

    def __repr__(self):
        return 'GuanliuClient(mode=simulated, origin=http://127.0.0.1:%d)' % self.__port

    def __reduce__(self):
        raise TypeError('GuanliuClient does not serialize credentials')

    def __request(self, path, execution=False, headers=None, post_body=None):
        # HTTPConnection never consults proxy environment variables or follows redirects.
        connection = http.client.HTTPConnection('127.0.0.1', self.__port, timeout=self.__timeout)
        expired = threading.Event()
        active_socket = [None]

        def expire():
            expired.set()
            sock = active_socket[0] or connection.sock
            if sock is not None:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError:
                    pass

        timer = threading.Timer(self.__timeout, expire)
        timer.daemon = True
        timer.start()
        try:
            connection.connect()
            active_socket[0] = connection.sock
            if expired.is_set():
                _fail('local_transport_error', execution)
            request_headers = {'Accept': 'application/json'}
            request_headers.update(headers or {})
            payload = None
            if post_body is not None:
                payload = json.dumps(post_body, ensure_ascii=False).encode('utf-8')
                if len(payload) > 16384:
                    _fail('invalid_params')
                request_headers.update({'Content-Type':'application/json', 'Origin':'http://127.0.0.1:%d' % self.__port})
            connection.request('POST' if post_body is not None else 'GET', path, body=payload, headers=request_headers)
            response = connection.getresponse()
            if response.status < 200 or response.status >= 600 or 300 <= response.status < 400:
                _fail('invalid_response', execution)
            data = bytearray()
            while True:
                if expired.is_set():
                    _fail('local_transport_error', execution)
                chunk = response.read1(65536)
                if not chunk:
                    break
                data.extend(chunk)
                if len(data) > _MAX_BYTES:
                    _fail('response_too_large', execution)
            if expired.is_set():
                _fail('local_transport_error', execution)
            try:
                body = json.loads(data.decode('utf-8'), parse_constant=lambda _: _fail('invalid_response', execution))
            except (ValueError, UnicodeError):
                _fail('invalid_response', execution)
            if not isinstance(body, dict) or self.__key in json.dumps(body):
                _fail('invalid_response', execution)
            return {'status': response.status, 'body': body}
        except GuanliuError:
            raise
        except Exception:
            raise GuanliuError('local_transport_error', execution) from None
        finally:
            timer.cancel()
            connection.close()

    def catalog(self):
        if self.__cached is not None and time.monotonic() - self.__cached_at < 60:
            return copy.deepcopy(self.__cached)
        response = self.__request('/catalog.json')
        if response['status'] != 200 or not _catalog_valid(response['body']):
            _fail('invalid_catalog')
        self.__cached = response['body']
        self.__cached_at = time.monotonic()
        return copy.deepcopy(self.__cached)

    def __input(self, capability, params, method='GET'):
        if method not in ('GET','POST') or not isinstance(capability,str) or len(capability)>200 or type(params) is not dict or len(params)>32:
            _fail('invalid_params')
        if any(not isinstance(k,str) or not _parameter_value(v) for k,v in params.items()):
            _fail('invalid_params')
        params=copy.deepcopy(params)
        try:
            encoded=json.dumps(params,ensure_ascii=False)
            if self.__key in encoded or len(encoded.encode('utf-8'))>16384:
                _fail('invalid_params')
        except (ValueError,UnicodeError):
            _fail('invalid_params')
        cap=next((item for item in self.catalog()['capabilities'] if item['id']==capability),None)
        if cap is None:
            _fail('capability_not_found')
        operation=cap if method=='GET' else next((op for op in cap.get('operations',[]) if op.get('method')=='POST'),None)
        if operation is None or not isinstance(operation.get('parameters'),list) or (method=='POST' and cap['path'] not in _POST_PATHS):
            _fail('invalid_params')
        names={param['name'] for param in operation['parameters']}
        if any(name not in names for name in params):
            _fail('invalid_params')
        query=urllib.parse.urlencode({k:','.join(v) if isinstance(v,list) else str(v).lower() if type(v) is bool else v for k,v in params.items()})
        if method=='GET' and len(query)+1>12000:
            _fail('invalid_params')
        return cap,query,params

    def quote(self, capability, params, *, max_credits=None, method='GET'):
        if (max_credits is not None and (type(max_credits) is not int or not 1 <= max_credits <= 1000000)) or (type(params) is dict and 'capability' in params):
            _fail('invalid_params')
        _, query, input_params = self.__input(capability, params, method)
        query = urllib.parse.urlencode({'capability': capability}) + ('&' + query if query else '')
        if method == 'GET' and len(query) + 1 > 12000:
            _fail('invalid_params')
        headers = {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'}
        if max_credits is not None:
            headers['X-Guanliu-Max-Credits'] = str(max_credits)
        response = self.__request('/v1/quote' if method == 'POST' else '/v1/quote?' + query, False, headers, {'capability':capability,'params':input_params,'method':'POST'} if method == 'POST' else None)
        status, body = response['status'], response['body']
        meta, data, code = body.get('meta'), body.get('data'), body.get('code')
        safe = isinstance(meta, dict) and meta.get('mode') == 'simulated' and meta.get('provider') == 'none' and meta.get('environment') == 'local_sandbox' and meta.get('readOnly') is True and type(meta.get('reservedCredits')) is int and meta['reservedCredits'] == 0 and type(meta.get('creditsDebited')) is int and meta['creditsDebited'] == 0 and meta.get('realMoneyCharged') is False
        if not isinstance(code, str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,99}', code) or ('meta' in body and not safe):
            _fail('invalid_response')
        if status < 400 and (status != 200 or code != 'ok' or not safe or not isinstance(data, dict) or data.get('capability') != capability or data.get('mode') != 'simulated' or data.get('currency') != 'TEST_CREDIT' or type(data.get('costCredits')) is not int or data['costCredits'] < 1 or type(data.get('eligible')) is not bool or not isinstance(data.get('blockers'), list)):
            _fail('invalid_response')
        return response

    def account(self):
        response = self.__request('/v1/account', False, {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'})
        return _read_response(response, _valid_account)

    def usage(self, filters=None):
        query = _usage_filters({} if filters is None else filters)
        path = '/v1/usage?' + urllib.parse.urlencode({key: value for key, value in query.items() if value is not None and value != ''})
        response = self.__request(path, False, {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'})
        return _read_response(response, lambda data: _valid_usage(data, query))

    def calls(self, filters=None):
        query = _calls_filters({} if filters is None else filters)
        path = '/v1/calls?' + urllib.parse.urlencode({k: v for k, v in query.items() if v is not None and v != ''})
        response = self.__request(path, False, {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'})
        return _read_response(response, lambda data: _valid_calls(data, query))

    def receipt(self, request_id):
        if not _identity(request_id):
            _fail('invalid_params')
        request_id = request_id.lower()
        response = self.__request('/v1/calls/' + request_id, False, {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'})
        return _read_response(response, lambda data: _valid_receipt(data, request_id))

    def result(self, request_id, *, view=None, fields=None):
        if not _identity(request_id):
            _fail('invalid_params')
        request_id = request_id.lower()
        query = _projection_query(view, fields)
        response = self.__request('/v1/calls/' + request_id + '/result' + ('?' + query if query else ''), False, {'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'simulated'})
        return _read_response(response, lambda data: _valid_receipt(data, request_id, True))

    def standing(self, idempotency_key):
        if not isinstance(idempotency_key,str) or not re.fullmatch(r'[\x21-\x7e]{1,255}',idempotency_key) or self.__key in idempotency_key:
            _fail('invalid_params')
        response=self.__request('/v1/calls?'+urllib.parse.urlencode({'idempotency_key':idempotency_key}),False,{'Authorization':'Bearer '+self.__key,'X-Guanliu-Mode':'simulated'})
        return _read_response(response,lambda data:_valid_standing(data,idempotency_key))

    def create_run(self, value, *, idempotency_key):
        body=_run_input(value)
        if not isinstance(idempotency_key,str) or not re.fullmatch(r'[\x21-\x7e]{1,128}',idempotency_key) or self.__key in idempotency_key or self.__key in json.dumps(body):
            _fail('invalid_params')
        response=self.__request('/v1/runs',True,{'Authorization':'Bearer '+self.__key,'X-Guanliu-Mode':'simulated','Idempotency-Key':idempotency_key},body)
        status,out=response['status'],response['body']
        meta,data=out.get('meta'),out.get('data')
        if not isinstance(out.get('code'),str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,99}',out['code']) or (meta is not None and (not isinstance(meta,dict) or not _readonly_meta({**meta,'readOnly':True}))):
            _fail('invalid_response',True)
        if status<400 and (status!=200 or out['code']!='ok' or not isinstance(data,dict) or not _identity(data.get('run_id')) or not _timestamp(data.get('expires_at')) or data.get('currency')!='TEST_CREDIT' or type(data.get('replayed')) is not bool or not isinstance(meta,dict) or meta.get('readOnly') is not False):
            _fail('invalid_response',True)
        return response

    def run(self, run_id):
        if not _identity(run_id):
            _fail('invalid_params')
        run_id=run_id.lower()
        response=self.__request('/v1/runs/'+run_id,False,{'Authorization':'Bearer '+self.__key,'X-Guanliu-Mode':'simulated'})
        return _read_response(response,lambda data:_valid_run(data,run_id))

    def call(self, capability, params, *, idempotency_key, scenario='success', max_credits=None, method='GET', run_id=None):
        if run_id is not None and not _identity(run_id):
            _fail('invalid_params')
        if not isinstance(idempotency_key, str) or not re.fullmatch(r'[\x21-\x7e]{1,128}', idempotency_key) or self.__key in idempotency_key or scenario not in ('success', 'failure', 'timeout') or (max_credits is not None and (type(max_credits) is not int or not 1 <= max_credits <= 1000000)):
            _fail('invalid_params')
        cap, query, input_params = self.__input(capability, params, method)
        response = self.__request(cap['path'] + ('?' + query if method == 'GET' and query else ''), True, {
            'Authorization': 'Bearer ' + self.__key,
            'X-Guanliu-Mode': 'simulated',
            'X-Guanliu-Mock-Scenario': scenario,
            'Idempotency-Key': idempotency_key,
            **({'X-Guanliu-Max-Credits': str(max_credits)} if max_credits is not None else {}),
            **({'X-Run-Id': run_id.lower()} if run_id is not None else {}),
        }, input_params if method == 'POST' else None)
        status, body = response['status'], response['body']
        code = body.get('code')
        if not isinstance(code, str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,99}', code) or ('meta' in body and not _simulation(body)):
            _fail('invalid_response', True)
        if status < 400:
            if status not in (200, 202) or not _simulation(body) or not isinstance(body.get('request_id'), str):
                _fail('invalid_response', True)
            if status == 200 and code != 'ok':
                _fail('invalid_response', True)
            if status == 202 and (code != 'gateway_request_pending' or not isinstance(body['meta'].get('execution'), dict) or body['meta']['execution'].get('state') != 'pending'):
                _fail('invalid_response', True)
        return response

# Explicit live reads; never delegates to the simulated execution client.
_LIVE_STATES = ('pending', 'success', 'failure', 'unknown')
_LIVE_PROVIDERS = ('tikhub', 'scrapecreators', 'twitterapi')
_CUSTOMER_SECRET = re.compile(r'gl_(?:test|live)_[A-Za-z0-9_-]{43}')


def _live_unit(provider, unit):
    return provider in _LIVE_PROVIDERS and unit == ('USD_micros' if provider == 'tikhub' else 'credits')


def _live_meta(meta):
    return isinstance(meta, dict) and meta.get('mode') == 'live' and meta.get('funding') == 'free_trial' and meta.get('provider') == 'none' and meta.get('environment') == 'customer_live_free_trial' and meta.get('readOnly') is True and type(meta.get('requestsDispatched')) is int and meta['requestsDispatched'] == 0 and type(meta.get('reservedUnits')) is int and meta['reservedUnits'] == 0 and meta.get('realMoneyCharged') is False


def _live_base(data):
    return isinstance(data, dict) and data.get('scope') == 'current_key' and _identity(data.get('keyId')) and _timestamp(data.get('asOf')) and data.get('timezone') == 'UTC' and data.get('funding') == 'free_trial' and data.get('customerAmount') == '0' and data.get('supplierActualCost') == 'unknown'


def _live_filters(value, kind):
    if type(value) is not dict or any(k not in (kind, 'provider', 'capability', 'from', 'to', 'page', 'pageSize') for k in value):
        _fail('invalid_params')
    value = value.copy()
    for k, v in value.items():
        valid = v in ('all',) + _LIVE_STATES if k == kind else v in ('',) + _LIVE_PROVIDERS if k == 'provider' else v == '' or _capability_id(v) if k == 'capability' else _calendar_date(v) if k in ('from', 'to') else _integer(v, 1, 1000000) if k == 'page' else type(v) is int and v in (20, 50, 100)
        if not valid or isinstance(v, str) and _CUSTOMER_SECRET.search(v):
            _fail('invalid_params')
    if value.get('from') and value.get('to') and value['from'] > value['to']:
        _fail('invalid_params')
    return {kind: value.get(kind, 'all'), 'provider': value.get('provider', ''), 'capability': value.get('capability', ''), 'from': value.get('from'), 'to': value.get('to'), 'page': value.get('page', 1), 'pageSize': value.get('pageSize', 20)}


def _valid_live_account(data):
    if not _live_base(data):
        return False
    key, grants = data.get('key'), data.get('grants')
    if not isinstance(key, dict) or key.get('id') != data['keyId'] or not isinstance(key.get('name'), str) or not isinstance(key.get('prefix'), str) or not re.fullmatch(r'gl_live_[A-Za-z0-9_-]{8}', key['prefix']) or not isinstance(key.get('capabilities'), list) or not all(_capability_id(x) for x in key['capabilities']) or not _timestamp(key.get('createdAt')) or not _timestamp(key.get('expiresAt')) or not isinstance(grants, list) or len(grants) > 3:
        return False
    providers = set()
    for g in grants:
        if not isinstance(g, dict) or g.get('scope') != 'current_account' or not _live_unit(g.get('provider'), g.get('unit')) or g.get('status') not in ('active', 'expired', 'revoked', 'missing') or g['provider'] in providers:
            return False
        providers.add(g['provider'])
        if g['status'] == 'missing':
            if 'expiresAt' not in g or g['expiresAt'] is not None or 'quota' not in g or g['quota'] is not None:
                return False
        else:
            q = g.get('quota')
            if not _timestamp(g.get('expiresAt')) or not isinstance(q, dict) or not all(_integer(q.get(k)) for k in ('requestLimit', 'usedRequests', 'remainingRequests', 'reservedUnitLimit', 'reservedUnits', 'remainingUnits')) or q['remainingRequests'] != max(0, q['requestLimit'] - q['usedRequests']) or q['remainingUnits'] != max(0, q['reservedUnitLimit'] - q['reservedUnits']):
                return False
    return True


def _valid_live_call(row, key_id):
    if not isinstance(row, dict) or not _identity(row.get('requestId')) or row.get('keyId') != key_id or row.get('provider') not in _LIVE_PROVIDERS or not _capability_id(row.get('capability')) or row.get('state') not in _LIVE_STATES or not _timestamp(row.get('createdAt')) or not _timestamp(row.get('deadlineAt')) or type(row.get('deadlineExpired')) is not bool or not _integer(row.get('httpStatus'), 200, 599) or type(row.get('resultAvailable')) is not bool or row.get('customerAmount') != '0' or row.get('supplierActualCost') != 'unknown':
        return False
    r = row.get('reservation')
    if not isinstance(r, dict) or not _integer(r.get('amount')) or not _live_unit(row['provider'], r.get('unit')) or r.get('kind') != 'conservative_estimate' or r.get('retained') is not True:
        return False
    return 'completedAt' in row and row['completedAt'] is None and row['httpStatus'] == 202 and row['resultAvailable'] is False if row['state'] == 'pending' else _timestamp(row.get('completedAt'))


def _valid_live_list(data, query):
    if not _live_base(data) or not isinstance(data.get('filters'), dict) or any(k not in data['filters'] or data['filters'][k] != v for k, v in query.items() if k not in ('page', 'pageSize')) or not _integer(data.get('page'), 1) or data['page'] != query['page'] or not _integer(data.get('pageSize')) or data['pageSize'] != query['pageSize'] or not _integer(data.get('total')) or not _integer(data.get('pages'), 1) or data['pages'] != max(1, math.ceil(data['total'] / query['pageSize'])) or not isinstance(data.get('items'), list) or len(data['items']) > query['pageSize'] or not isinstance(data.get('summary'), dict):
        return False
    s = data['summary']
    if not all(_integer(s.get(k)) for k in ('requests',) + _LIVE_STATES) or s['requests'] != data['total'] or sum(s[k] for k in _LIVE_STATES) != data['total'] or not isinstance(s.get('reservations'), list) or len(s['reservations']) > 3:
        return False
    providers = set()
    for r in s['reservations']:
        if not isinstance(r, dict) or not _live_unit(r.get('provider'), r.get('unit')) or not _integer(r.get('amount')) or not _integer(r.get('requests')) or r['provider'] in providers:
            return False
        providers.add(r['provider'])
    return sum(r['requests'] for r in s['reservations']) == data['total'] and all(_valid_live_call(row, data['keyId']) for row in data['items'])


def _valid_live_receipt(data, request_id, result=False):
    if not _live_base(data) or not _valid_live_call(data.get('call'), data['keyId']) or data['call']['requestId'] != request_id:
        return False
    if not result:
        return True
    response = data.get('response')
    if not isinstance(response, dict) or not _integer(response.get('status'), 200, 599) or response['status'] != data['call']['httpStatus'] or not isinstance(response.get('body'), dict):
        return False
    body, call = response['body'], data['call']
    meta = body.get('meta')
    billing = meta.get('billing') if isinstance(meta, dict) else None
    return call['resultAvailable'] and body.get('request_id') == request_id and isinstance(meta, dict) and meta.get('mode') == 'live' and meta.get('funding') == 'free_trial' and meta.get('provider') == call['provider'] and meta.get('capability') == call['capability'] and meta.get('replayed') is True and body.get('retryable') is False and isinstance(billing, dict) and billing.get('status') == 'free_trial' and billing.get('currency') == 'USD' and billing.get('charged') is False and billing.get('amount') == '0' and billing.get('supplier_actual_cost') == 'unknown' and isinstance(billing.get('reservation'), dict) and type(billing['reservation'].get('amount')) is int and billing['reservation']['amount'] == call['reservation']['amount'] and billing['reservation'].get('unit') == call['reservation']['unit'] and billing['reservation'].get('kind') == 'conservative_estimate'


def _valid_live_standing(data):
    return _live_base(data) and data.get('idempotencyScope') == 'current_account' and data.get('state') in ('free', 'occupied_by_other_key') + _LIVE_STATES and (('call' in data and data['call'] is None) if data['state'] in ('free', 'occupied_by_other_key') else _valid_live_call(data.get('call'), data['keyId']) and data['call']['state'] == data['state']) and 'idempotency_key' not in data


def _live_response(response, validate):
    status, body = response['status'], response['body']
    if not isinstance(body.get('code'), str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,99}', body['code']) or 'meta' in body and not _live_meta(body['meta']):
        _fail('invalid_response')
    if status < 400 and (status != 200 or body['code'] != 'ok' or not _live_meta(body.get('meta')) or not validate(body.get('data'))):
        _fail('invalid_response')
    return response


class GuanliuLiveReadClient:
    __slots__ = ('__key', '__port', '__timeout')

    def __init__(self, api_key, port=4321, timeout_ms=5000):
        if not isinstance(api_key, str) or not re.fullmatch(r'gl_live_[A-Za-z0-9_-]{43}', api_key) or isinstance(port, bool) or not re.fullmatch(r'[0-9]{1,5}', str(port)) or not 1 <= int(port) <= 65535 or type(timeout_ms) is not int or not 1 <= timeout_ms <= 60000:
            _fail('invalid_config')
        self.__key, self.__port, self.__timeout = api_key, int(port), timeout_ms / 1000

    def __repr__(self):
        return 'GuanliuLiveReadClient(mode=live, read_only=True, origin=http://127.0.0.1:%d)' % self.__port

    def __reduce__(self):
        raise TypeError('GuanliuLiveReadClient does not serialize credentials')

    def __request(self, path, authenticate=True):
        connection = http.client.HTTPConnection('127.0.0.1', self.__port, timeout=self.__timeout)
        expired, active_socket = threading.Event(), [None]

        def expire():
            expired.set()
            sock = active_socket[0] or connection.sock
            if sock is not None:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError:
                    pass

        timer = threading.Timer(self.__timeout, expire)
        timer.daemon = True
        timer.start()
        try:
            connection.connect()
            active_socket[0] = connection.sock
            if expired.is_set():
                _fail('local_transport_error')
            headers = {'Accept': 'application/json'}
            if authenticate:
                headers.update({'Authorization': 'Bearer ' + self.__key, 'X-Guanliu-Mode': 'live'})
            connection.request('GET', path, headers=headers)
            response = connection.getresponse()
            if response.status < 200 or response.status >= 600 or 300 <= response.status < 400:
                _fail('invalid_response')
            data = bytearray()
            while True:
                if expired.is_set():
                    _fail('local_transport_error')
                chunk = response.read1(65536)
                if not chunk:
                    break
                data.extend(chunk)
                if len(data) > _MAX_BYTES:
                    _fail('response_too_large')
            if expired.is_set():
                _fail('local_transport_error')
            try:
                body = json.loads(data.decode('utf-8'), parse_constant=lambda _: _fail('invalid_response'))
            except (ValueError, UnicodeError):
                _fail('invalid_response')
            if not isinstance(body, dict) or _CUSTOMER_SECRET.search(json.dumps(body)):
                _fail('invalid_response')
            return {'status': response.status, 'body': body}
        except GuanliuError:
            raise
        except Exception:
            raise GuanliuError('local_transport_error') from None
        finally:
            timer.cancel()
            connection.close()

    def catalog(self):
        response = self.__request('/catalog.json', False)
        if response['status'] != 200 or not _catalog_valid(response['body']):
            _fail('invalid_catalog')
        return response['body']

    def account(self):
        return _live_response(self.__request('/v1/account'), _valid_live_account)

    def __list(self, path, filters, kind):
        query = _live_filters({} if filters is None else filters, kind)
        path += '?' + urllib.parse.urlencode({k: v for k, v in query.items() if v is not None and v != ''})
        return _live_response(self.__request(path), lambda data: _valid_live_list(data, query))

    def usage(self, filters=None):
        return self.__list('/v1/usage', filters, 'status')

    def calls(self, filters=None):
        return self.__list('/v1/calls', filters, 'state')

    def receipt(self, request_id):
        if not _identity(request_id):
            _fail('invalid_params')
        request_id = request_id.lower()
        return _live_response(self.__request('/v1/calls/' + request_id), lambda data: _valid_live_receipt(data, request_id))

    def result(self, request_id, *, view=None, fields=None):
        if not _identity(request_id):
            _fail('invalid_params')
        request_id, query = request_id.lower(), _projection_query(view, fields)
        if _CUSTOMER_SECRET.search(query):
            _fail('invalid_params')
        return _live_response(self.__request('/v1/calls/' + request_id + '/result' + ('?' + query if query else '')), lambda data: _valid_live_receipt(data, request_id, True))

    def standing(self, idempotency_key):
        if not isinstance(idempotency_key, str) or not re.fullmatch(r'[\x21-\x7e]{1,128}', idempotency_key) or _CUSTOMER_SECRET.search(idempotency_key):
            _fail('invalid_params')
        return _live_response(self.__request('/v1/calls/standing?' + urllib.parse.urlencode({'idempotency_key': idempotency_key})), _valid_live_standing)

    def call(self, *args, **kwargs):
        _fail('live_read_only')

    quote = call
    run = call
    create_run = call
    read_more = call
