"""Normalized authored REFER/NOTIFY records, not a general SIP parser or call."""
import re,json
def inspect(records):
    subscriptions={};log=[]
    for row in records:
        k=tuple(row['subscription'])
        if len(k)!=4:raise ValueError('declared dialog Call-ID/local-tag/remote-tag plus Event-id')
        if row['kind']=='refer_accepted':
            if k in subscriptions or row['status']not in [200,202]:raise ValueError('accepted REFER fixture only')
            subscriptions[k]={'accepted_status':row['status'],'final_sipfrag':None,'provisional':[],'notify_transaction_responses':[]}
        elif row['kind']=='notify':
            if k not in subscriptions:raise ValueError('unknown subscription; do not assign to the most recent REFER')
            m=re.fullmatch(r'SIP/2.0 ([1-6][0-9]{2}) ([^\r\n]+)\r\n',row['body'])
            if not m:raise ValueError('limited single status-line sipfrag subset')
            code=int(m[1]);entry=subscriptions[k]
            if entry['final_sipfrag']is not None:raise ValueError('after-final sequence outside fixture')
            if code<200:entry['provisional'].append(code)
            else:entry['final_sipfrag']=code
            if row['notify_response']!=200:raise ValueError('this fixture models successful NOTIFY delivery only')
            entry['notify_transaction_responses'].append(row['notify_response'])
            log.append({'subscription':list(k),'body_status':code,'notify_transaction_status':200})
        else:raise ValueError('unsupported record')
    return {'subscriptions':[{'subscription':list(k),**v,'referred_result':'unknown_no_final_notify'if v['final_sipfrag']is None else'sip_success_not_business_outcome'if 200<=v['final_sipfrag']<300 else'sip_failure'}for k,v in subscriptions.items()],'notify_trace':log}
def demo():
    a=['new-subscription-a','la','ra','41'];b=['new-subscription-b','lb','rb','52']
    records=[{'kind':'refer_accepted','subscription':a,'status':200},{'kind':'refer_accepted','subscription':b,'status':200},
      {'kind':'notify','subscription':a,'body':'SIP/2.0 180 Ringing\r\n','notify_response':200},
      {'kind':'notify','subscription':b,'body':'SIP/2.0 100 Trying\r\n','notify_response':200},
      {'kind':'notify','subscription':b,'body':'SIP/2.0 503 Service Unavailable\r\n','notify_response':200},
      {'kind':'notify','subscription':a,'body':'SIP/2.0 200 OK\r\n','notify_response':200}]
    result=inspect(records);assert [x['final_sipfrag']for x in result['subscriptions']]==[200,503]
    assert all(x['notify_transaction_responses']==[200,200]for x in result['subscriptions'])
    partial=inspect(records[:4]);assert all(x['referred_result']=='unknown_no_final_notify'for x in partial['subscriptions'])
    legacy=inspect([{**records[0],'status':202}]);assert legacy['subscriptions'][0]['referred_result']=='unknown_no_final_notify'
    try:inspect([records[0],{**records[2],'subscription':b}])
    except ValueError:unknown_rejected=True
    else:raise AssertionError('unmatched NOTIFY assigned')
    return {'authored_records_not_network_capture':records,'result':result,'without_final_notify':partial,'legacy_202_received_as_accepted_not_completion':legacy,'unknown_subscription_rejected':unknown_rejected,'modern_scope':'Both accepted REFERs use 200. Each starts a separate subscription dialog to a declared GRUU-capable target; normalized identity resolved beforehand, not modern in-dialog REFER reuse. Existing call correlation/Target-Dialog not parsed. Full RFC6665 state, early NOTIFY race, retransmission, authentication and actual transfer not implemented. sipfrag200 is not human acceptance or resolved customer case.','real_calls_or_messages_sent':False}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
