"""Authored bounded, non-mutating string-column CSV profile. No file/network access."""
import csv,io,json,hashlib,platform
def profile(raw):
 if not isinstance(raw,bytes) or len(raw)>16384:raise ValueError('byte budget')
 text=raw.decode('utf-8-sig',errors='strict');rd=csv.reader(io.StringIO(text,newline=''),delimiter=',',quotechar='"',doublequote=True,skipinitialspace=False,strict=True)
 rows=list(rd)
 if not rows or not rows[0] or len(rows)>101 or len(rows[0])>20:raise ValueError('shape budget')
 header=rows[0]
 if any(not h.strip() for h in header) or len(set(header))!=len(header):raise ValueError('empty or duplicate header')
 if any(len(r)!=len(header) for r in rows[1:]):raise ValueError('ragged record')
 columns=[]
 for i,name in enumerate(header):
  vals=[r[i] for r in rows[1:]]
  if any(len(v)>1024 for v in vals):raise ValueError('cell budget')
  columns.append({'name':name,'denominator_records':len(vals),'empty_exact':sum(v=='' for v in vals),'whitespace_only_nonempty':sum(v!='' and v.isspace() for v in vals),'distinct_exact':len(set(vals)),'max_codepoints':max(map(len,vals),default=0)})
 return {'bom_removed_for_parse':raw.startswith(b'\xef\xbb\xbf'),'records_excluding_header':len(rows)-1,'physical_lines':len(text.splitlines()),'columns':columns,'original_sha256':hashlib.sha256(raw).hexdigest(),'type_inference':False,'source_rewritten':False}
def demo():
 text='id,note,status\r\n001,"الف,ب",\r\n002,"دو\nخط", \r\n003,"گفت ""بله""",open\r\n004,,open\r\n'
 raw=b'\xef\xbb\xbf'+text.encode();before=bytes(raw);out=profile(raw)
 assert out['records_excluding_header']==4 and out['physical_lines']==6
 assert out['columns']==[{'name':'id','denominator_records':4,'empty_exact':0,'whitespace_only_nonempty':0,'distinct_exact':4,'max_codepoints':3},{'name':'note','denominator_records':4,'empty_exact':1,'whitespace_only_nonempty':0,'distinct_exact':4,'max_codepoints':9},{'name':'status','denominator_records':4,'empty_exact':1,'whitespace_only_nonempty':1,'distinct_exact':3,'max_codepoints':4}]
 assert raw==before
 invalid=[b'a,a\n1,2\n',b'a, \n1,2\n',b'a,b\n1\n',b'a,b\n1,2,3\n',b'a,b\n\n',b'a\n"unterminated',b'\xff']
 rejected=[]
 for r in invalid:
  try:profile(r)
  except (ValueError,UnicodeError,csv.Error):rejected.append(r.hex())
  else:raise AssertionError('accepted invalid fixture')
 empty=profile(b'id,note\n');assert empty['records_excluding_header']==0 and all(c['max_codepoints']==0 for c in empty['columns'])
 assert profile(b'id,note\n001, \n')['columns'][1]['whitespace_only_nonempty']==1
 return {'runtime':platform.python_version(),'authored_csv':text,'result':out,'rejected_fixtures_hex':rejected,'header_only_result':empty,'all_assertions_passed':True}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
