#!/usr/bin/env python3
"""AstraNL Robot Passport v1 - CONFORMANCE TEST.
Anyone can prove an implementation conforms:
    python3 conformance.py https://astranl.com 479
Exit 0 = CONFORMS, 1 = violations listed. Only stdlib required."""
import json
import sys
import urllib.request


def check(base, rid):
    url = f'{base}/api/robot-passport/{rid}'
    with urllib.request.urlopen(url, timeout=15) as r:
        d = json.loads(r.read().decode())
    v = []
    if d.get('ok') is not True:
        v.append('envelope: ok must be true')
    p = d.get('passport')
    if not isinstance(p, dict):
        v.append('envelope: passport object required')
        return v
    for f in ('passport_id', 'schema', 'identity', 'capability',
              'lifecycle', 'provenance', 'honest_gaps'):
        if f not in p:
            v.append(f'passport: required field missing: {f}')
    if 'schema' in p and 'v1' not in str(p['schema']):
        v.append('schema: version must be 1.x for v1 conformance')
    if 'identity' in p and not isinstance(p['identity'], dict):
        v.append('identity: must be object')
    if 'honest_gaps' not in p:
        pass
    elif not isinstance(p['honest_gaps'], (list, dict)):
        v.append('honest_gaps: must be array or object (truth law field)')
    return v


if __name__ == '__main__':
    base = sys.argv[1] if len(sys.argv) > 1 else 'https://astranl.com'
    rid = sys.argv[2] if len(sys.argv) > 2 else '479'
    try:
        violations = check(base.rstrip('/'), rid)
    except Exception as e:
        print(f'FAIL: endpoint unreachable or invalid JSON: {e}')
        sys.exit(1)
    if violations:
        print('NOT CONFORMANT:')
        for x in violations:
            print(' -', x)
        sys.exit(1)
    print(f'CONFORMS: {base}/api/robot-passport/{rid} satisfies Robot Passport v1')
    sys.exit(0)
