"""Two-hop lookup over a custom authored triple list, not an RDF engine."""
import json
NODES={'b1':'دفتر آبی','b2':'دفتر سفید','a1':'آراد','a2':'آراد','c1':'شهر نمونه'}
TRIPLES=[('b1','written_by','id','a1'),('b2','written_by','id','a2'),('a1','lives_in','id','c1'),('b1','title','literal','دفتر آبی'),('b2','title','literal','دفتر سفید')]
def lookup(subject,predicate,triples):return [(i,value) for i,(s,p,kind,value) in enumerate(triples) if s==subject and p==predicate and kind=='id']
def author_cities(book,triples):
    if book not in NODES:raise ValueError('unknown node id')
    rows=[]
    for first,author in lookup(book,'written_by',triples):
        for second,city in lookup(author,'lives_in',triples):rows.append({'author_id':author,'city_id':city,'supporting_triple_indices':[first,second]})
    return rows
if __name__=='__main__':
    a=author_cities('b1',TRIPLES);b=author_cities('b2',TRIPLES)
    assert a==[{'author_id':'a1','city_id':'c1','supporting_triple_indices':[0,2]}] and b==[]
    assert NODES['a1']==NODES['a2'] and 'a1'!='a2'
    reversed_edge=[('a1','written_by','id','b1')]+TRIPLES[1:]
    assert author_cities('b1',reversed_edge)==[]
    literal_edge=[('b1','written_by','literal','a1')]+TRIPLES[1:]
    assert author_cities('b1',literal_edge)==[]
    print(json.dumps({'book1_results':a,'book2_results':b,'book2_absence_means':'no path recorded, not proof of no city','RDF_engine_run':False,'real_world_facts':False},ensure_ascii=False,indent=2))
