"""Original direct overlap-add stream with bounded state, not FFT or SciPy."""
import numpy as np,json
from fractions import Fraction as F

def ints(x,limit):
 if not isinstance(x,list) or not 1<=len(x)<=limit or any(type(v)!=int or abs(v)>100 for v in x):raise ValueError('bounded int vector')
def direct(x,h):return [sum(F(x[k])*h[j-k] for k in range(len(x)) if 0<=j-k<len(h)) for j in range(len(x)+len(h)-1)]
class Stream:
 def __init__(self,h):ints(h,5);self.h=h;self.tail=[F(0)]*(len(h)-1);self.final=False;self.count=0;self.trace=[]
 def add(self,chunk):
  if self.final:raise ValueError('already finalized')
  ints(chunk,8)
  if self.count+len(chunk)>16:raise ValueError('input budget')
  local=direct(chunk,self.h);combined=local[:]
  for j,v in enumerate(self.tail):combined[j]+=v
  emit=combined[:len(chunk)];self.tail=combined[len(chunk):];assert len(self.tail)==len(self.h)-1
  self.trace.append({'offset':self.count,'chunk':chunk,'local':list(map(str,local)),'after_carry':list(map(str,combined)),'emit':list(map(str,emit)),'tail':list(map(str,self.tail))});self.count+=len(chunk);return emit
 def flush(self):
  if self.final or not self.count:raise ValueError('double or empty flush')
  self.final=True;return self.tail[:]
def run(x,h,parts):
 s=Stream(h);got=[];pos=0
 for size in parts:got+=s.add(x[pos:pos+size]);pos+=size
 assert pos==len(x);got+=s.flush();assert got==direct(x,h) and np.allclose([float(v) for v in got],np.convolve(x,h,'full'));return got,s

def demo():
 x=[1,2,3,4,5];h=[1,-1,2];out,s=run(x,h,[2,2,1]);assert out==[1,1,3,5,7,3,10]
 allparts=[]
 for mask in range(16):
  cuts=[0]+[i for i in range(1,5) if mask>>(i-1)&1]+[5];parts=[b-a for a,b in zip(cuts,cuts[1:])];run(x,h,parts);allparts.append(parts)
 wrong_concat=[v for row in s.trace for v in row['local']];wrong_trim=[v for row in s.trace for v in row['local'][:len(row['chunk'])]];assert len(wrong_concat)==11 and list(map(F,wrong_trim))!=out[:5]
 for xx,hh,parts in [([1,0,0],[1,2,3],[1,2]),(x,[2],[2,2,1]),([3],[1,2,3,4],[1])]:run(xx,hh,parts)
 rej=[]
 for label,fn in [('empty_filter',lambda:Stream([])),('empty_chunk',lambda:Stream(h).add([])),('bool',lambda:Stream(h).add([True])),('oversize_chunk',lambda:Stream(h).add([1]*9)),('empty_flush',lambda:Stream(h).flush()),('double_flush',s.flush),('append_final',lambda:s.add([1]))]:
  try:fn()
  except ValueError:rej.append(label)
  else:raise AssertionError(label)
 return {'input':x,'filter':h,'trace':s.trace,'full_output':list(map(str,out)),'wrong_local_concat':wrong_concat,'wrong_local_trimmed':wrong_trim,'all16_positive_partitions':allparts,'invalid_cases_rejected':rej,'numpy_version':np.__version__,'scope':'Own direct convolution blocks; exact global coefficient loop and actual NumPy convolve oracle. Tail M-1 state; retained full report O(N), not whole memory O(M), no FFT/SciPy/audio/performance or latency measurement.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
