"""Mekler reference trial client. Wallet signatures only; no payment capability.

Requires Python 3.11+, x402==2.24.0 and eth-account==0.13.7, signinwithethereum==5.0.1, abnf==2.8.3.
Keep keys and input files private. No redirects or automatic paid fallback.
"""
import argparse
import asyncio
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import sys
from urllib.error import HTTPError
from urllib.request import Request, build_opener, HTTPRedirectHandler

ORIGIN = 'https://api.mekler.ai'
NETWORK = 'eip155:8453'
OPERATIONS = {
    'validateCsvDelivery': '/v1/data/csv/validate-data',
    'validateAcceptanceSpec': '/v1/data/csv/validate-column-spec',
    'checkSources': '/v1/research/citations/check-source-overlap',
    'extractPage': '/v1/web/pages/extract-static-content',
}


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, allow_nan=False).encode('ascii')


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


def send(url, body, headers):
    if url not in {ORIGIN + path for path in OPERATIONS.values()}:
        raise ValueError('unexpected_trial_destination')
    req = Request(url, data=canonical(body), headers=headers, method='POST')
    try:
        response = build_opener(NoRedirect()).open(req, timeout=30)
    except HTTPError as exc:
        response = exc
    with response:
        data = response.read(1048577)
        if len(data) > 1048576:
            raise ValueError('response_too_large')
        return response.status, json.loads(data)


class Signer:
    def __init__(self, account):
        self.account, self.address = account, account.address

    async def sign_message(self, *, message, account=None):
        from eth_account.messages import encode_defunct
        return '0x' + self.account.sign_message(encode_defunct(text=message)).signature.hex()


async def execute(operation, body, signer, request_id, *, referral_code=None, transport=send):
    from x402.extensions.sign_in_with_x import create_siwx_payload
    if operation not in OPERATIONS or not isinstance(body, dict):
        raise ValueError('supported_trial_operation_and_json_object_required')
    if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}', request_id):
        raise ValueError('request_id_must_be_1_to_128_ascii_letters_digits_underscore_hyphen')
    url = ORIGIN + OPERATIONS[operation]
    headers = {'Content-Type': 'application/json', 'X-Mekler-Trial': 'true', 'Idempotency-Key': request_id}
    binding = {'operation': operation, 'body': body}
    if referral_code is not None:
        if not re.fullmatch(r'[A-Za-z0-9_-]{22,64}', referral_code):
            raise ValueError('invalid_referral_code')
        headers.update({'X-Mekler-Referral': referral_code, 'X-Mekler-Wallet': signer.address, 'X-Mekler-Network': NETWORK})
        binding['referral_code'] = referral_code
    status, result = transport(url, body, headers.copy())
    if status != 402:
        return status, result
    if result.get('accepts') != []:
        raise ValueError('refusing_payment_challenge_in_trial_mode')
    ext = result['extensions']['sign-in-with-x']
    info = ext['info']
    resource = 'urn:mekler:trial:' + hashlib.sha256(canonical(binding)).hexdigest()
    if (info.get('uri') != url or info.get('requestId') != request_id or info.get('resources') != [resource]
            or info.get('domain') != 'api.mekler.ai'):
        raise ValueError('trial_challenge_binding_mismatch')
    chain = next((c for c in ext['supportedChains'] if isinstance(c, dict) and c.get('chainId') == NETWORK), {})
    if chain.get('type') != 'eip191' or chain.get('signatureScheme') != 'eip191':
        raise ValueError('unexpected_signing_scheme')
    proof = await create_siwx_payload({**info, **chain}, signer, url)
    headers['SIGN-IN-WITH-X'] = base64.b64encode(canonical(proof.model_dump(by_alias=True, exclude_none=True))).decode('ascii')
    return transport(url, body, headers)


def load_key(path):
    from eth_account import Account
    fd = os.open(Path(path).expanduser(), os.O_RDONLY | os.O_NOFOLLOW)
    with os.fdopen(fd) as source:
        info = os.fstat(source.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
            raise ValueError('wallet_key_file_must_be_owned_by_you_and_mode_0600')
        return Account.from_key(source.read(1025).strip())


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--new-wallet', help='Explicitly create an unfunded Base wallet in a new private local file')
    parser.add_argument('--key-file')
    parser.add_argument('--operation', choices=sorted(OPERATIONS))
    parser.add_argument('--input', help='JSON input file')
    parser.add_argument('--request-id', help='Keep stable across identical retries')
    parser.add_argument('--referral-code', help='Optional code to bind into the signed request; no trial commission')
    args = parser.parse_args()
    try:
        if args.new_wallet:
            if any([args.key_file, args.operation, args.input, args.request_id, args.referral_code]):
                raise ValueError('wallet_creation_is_a_separate_explicit_step')
            from eth_account import Account
            account = Account.create()
            fd = os.open(Path(args.new_wallet).expanduser(), os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
            with os.fdopen(fd, 'w') as dest:
                dest.write(account.key.hex() + '\n')
                dest.flush(); os.fsync(dest.fileno())
            print(json.dumps({'wallet': account.address, 'network': NETWORK, 'funding_required': False}))
            return
        if not all([args.key_file, args.operation, args.input, args.request_id]):
            raise ValueError('key_file_operation_input_and_request_id_required')
        body = json.loads(Path(args.input).read_text())
        status, result = asyncio.run(execute(args.operation, body, Signer(load_key(args.key_file)), args.request_id, referral_code=args.referral_code))
        print(json.dumps({'http_status': status, 'operation': args.operation, 'request_id': args.request_id, 'result': result}, indent=2))
        if not 200 <= status < 300:
            raise SystemExit(2)
    except (ValueError, KeyError, StopIteration, OSError):
        print('Trial stopped. Check the offer, input, wallet-file permissions and request ID. No payment was attempted.', file=sys.stderr)
        raise SystemExit(1)


if __name__ == '__main__':
    main()
