import json, sys, time, urllib.error, urllib.request
BASE = 'https://api.jopex.co.tz/hustlers/api'
P = F = 0
def check(label, cond, extra=''):
    global P, F
    ok = bool(cond); P += ok; F += not ok
    print(f'  [{"PASS" if ok else "FAIL"}] {label}{(" — "+extra) if extra else ""}')
def call(method, path, body=None, token=None):
    req = urllib.request.Request(BASE + path,
        data=json.dumps(body).encode() if body is not None else None, method=method)
    req.add_header('Content-Type', 'application/json')
    if token: req.add_header('Authorization', f'Bearer {token}')
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            raw = r.read().decode(); return r.status, (json.loads(raw) if raw else None)
    except urllib.error.HTTPError as e:
        raw = e.read().decode()
        try: return e.code, json.loads(raw)
        except ValueError: return e.code, raw
    except Exception as e:
        return None, f'{type(e).__name__}: {e}'
print(f'Target: {BASE}\n')
st, b = call('GET', '/health');   check('health 200', st == 200, str(st)); check('status ok', isinstance(b, dict) and b.get('status') == 'ok', json.dumps(b) if b else '')
st, b = call('GET', '/products'); check('products 200 array', st == 200 and isinstance(b, list), str(st))
st, b = call('GET', '/sales');    check('401 unauth', st == 401, str(st))
phone = '07' + str(int(time.time()))[-8:]; pw = 'livetest1234'
st, b = call('POST', '/auth/register', {'name': 'Live Test', 'phone': phone, 'password': pw, 'password_confirm': pw}); check('register 201', st == 201, str(st))
token = b.get('token') if isinstance(b, dict) else None; check('register token', bool(token))
st, b = call('POST', '/auth/login', {'phone': phone, 'password': pw}); check('login 200', st == 200, str(st))
token = (b.get('token') if isinstance(b, dict) else token) or token
st, b = call('GET', '/auth/me', token=token); check('me 200', st == 200, str(st))
print(f'\n{P} passed, {F} failed'); sys.exit(1 if F else 0)
