from pathlib import Path
import wave,struct,math,json,hashlib
out=Path(__file__).parent; rate=44100; n=rate*2
left=[round(8191*math.sin(2*math.pi*440*i/rate)) if .2<=i/rate<.7 else 0 for i in range(n)]
right=[round(8191*math.sin(2*math.pi*880*i/rate)) if 1<=i/rate<1.5 else 0 for i in range(n)]
cases=[('reference',left,right),('swapped',right,left),('left-duplicated',left,left),('right-inverted',left,[-x for x in right]),('right-half',left,[int(x/2) for x in right])]
rows=[]
for name,L,R in cases:
    path=out/('channel-map-'+name+'.wav')
    with wave.open(str(path),'wb') as w:
        w.setnchannels(2);w.setsampwidth(2);w.setframerate(rate)
        w.writeframes(b''.join(struct.pack('<hh',a,b) for a,b in zip(L,R)))
    with wave.open(str(path),'rb') as w:
        channels=w.getnchannels();frames=w.getnframes();samples=list(struct.iter_unpack('<hh',w.readframes(frames)))
    A=[s[0] for s in samples];B=[s[1] for s in samples]
    rows.append({'case':name,'file':path.name,'channels':channels,'sample_rate':rate,'frames':frames,'seconds':frames/rate,'left_matches_reference_left':A==left,'right_matches_reference_right':B==right,'swapped_pair':A==right and B==left,'right_polarity_inverse':B==[-x for x in right],'right_half_integer':B==[int(x/2) for x in right],'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'scope':'Authored PCM signal transformation; not music service export, speaker wiring or hearing test'})
assert [(r['left_matches_reference_left'],r['right_matches_reference_right']) for r in rows]==[(True,True),(False,False),(True,False),(True,False),(True,False)]
assert [r['swapped_pair'] for r in rows]==[False,True,False,False,False]
assert rows[3]['right_polarity_inverse'] and rows[4]['right_half_integer']
out.joinpath('channel-map-results.json').write_text(json.dumps(rows,indent=2))
print(json.dumps(rows))
