#!/usr/bin/env python3
"""Python 3.10+. Standard library only. Set JEV_API_KEY, then run once.
Optional: JEV_INDUSTRY, JEV_SCENARIO, JEV_MESSAGE. No automatic POST retries.
"""
import uuid
import json
import os
import sys
import urllib.error
import urllib.request

BASE = 'https://nsr.stateset.com'
REQUEST_ID = os.environ.get('JEV_REQUEST_ID', str(uuid.uuid4()))


def request(path, body=None, key=None):
    headers = {'Accept': 'application/json'}
    if key:
        headers.update({'Content-Type': 'application/json', 'X-Jev-Api-Key': key, 'Idempotency-Key': REQUEST_ID})
    req = urllib.request.Request(BASE + path, headers=headers,
                                 data=None if body is None else json.dumps(body).encode())
    try:
        with urllib.request.urlopen(req, timeout=35) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        payload = json.loads(error.read())
        info = payload.get('error', {})
        print('Request failed:', info.get('code', error.code), file=sys.stderr)
        print(info.get('message', 'Request failed'), file=sys.stderr)
        print(info.get('next_action', 'Do not retry automatically.'), file=sys.stderr)
        if error.code == 429:
            print('Wait at least', error.headers.get('Retry-After', '60'), 'seconds.', file=sys.stderr)
        raise SystemExit(1) from None
    except (OSError, ValueError):
        raise SystemExit('Network or response error. Outcome unknown; do not retry automatically.') from None


def main():
    if '--status' in sys.argv:
        if not os.environ.get('JEV_REQUEST_ID') or not os.environ.get('JEV_API_KEY'):
            raise SystemExit('Set the original JEV_REQUEST_ID and the same JEV_API_KEY.')
        from urllib.parse import quote
        record = request('/api/jev/requests/' + quote(REQUEST_ID, safe=''), key=os.environ['JEV_API_KEY'])
        print(json.dumps(record, indent=2))
        return 0 if record.get('state') == 'completed' else 2
    catalog = request('/api/jev/catalog')
    if not catalog['live_available']:
        raise SystemExit('Live demo unavailable. Explore /jev/example.json instead.')
    industry = os.environ.get('JEV_INDUSTRY', 'retail')
    pack = next((p for p in catalog['packs'] if p['industry'] == industry), None)
    if not pack:
        raise SystemExit('Unknown industry. Choose one from /api/jev/catalog.')
    scenario = os.environ.get('JEV_SCENARIO', pack['scenarios'][0]['id'])
    if not any(s['id'] == scenario for s in pack['scenarios']):
        raise SystemExit('Scenario does not belong to this industry.')
    key = os.environ.get('JEV_API_KEY', '').strip()
    if not key:
        raise SystemExit('Set JEV_API_KEY to a direct TypeSafe key. Never put it in the message.')
    body = {'industry': industry, 'scenario': scenario}
    if 'JEV_MESSAGE' in os.environ:
        body['message'] = os.environ['JEV_MESSAGE']
    print('Request ID:', REQUEST_ID, 'Recover with GET /api/jev/requests/' + REQUEST_ID + ' and the same Jev key.', file=sys.stderr)
    envelope = request('/api/jev/decisions', body, key)
    if 'result' not in envelope:
        raise SystemExit('Request pending or unknown. Check original status before another inference.')
    result = envelope['result']
    print(json.dumps(envelope, indent=2))
    print('Decision:', result['decision'], '(no business action executed)')
    if result.get('routing', {}).get('band') == 'escalate' or result.get('refusal', {}).get('requires_human_review') or result.get('evidence', {}).get('requires_human_review'):
        print('Human review required. Do not automate a business action.')
    if result['decision'] == 'refused':
        print('Refused is a valid decision. Inspect the reason; the demo evidence cannot be changed.')


if __name__ == '__main__':
    sys.exit(main())
