"""Python 3.12+: preflight container depth, validate, then export id/payload CSV.
Root container counts as depth 1. Scalars count as depth 0.
This bounded demo requires an array of id/payload objects and string leaves.
"""
import argparse,csv,json
from pathlib import Path
MAX_BYTES=1000000
def check_depth(text,limit):
    if not 1<=limit<=64:raise ValueError('depth limit must be 1..64')
    stack=[];quoted=False;escaped=False;peak=0
    for ch in text:
        if quoted:
            if escaped:escaped=False
            elif ch=='\\':escaped=True
            elif ch=='"':quoted=False
            continue
        if ch=='"':quoted=True
        elif ch in '[{':
            stack.append(ch);peak=max(peak,len(stack))
            if len(stack)>limit:raise ValueError('container depth exceeds '+str(limit))
        elif ch in ']}':
            if not stack or stack.pop()!=('[' if ch==']' else '{'):
                raise ValueError('mismatched container delimiters')
    if quoted or stack:raise ValueError('unfinished string or container')
    return peak
def unique(pairs):
    out={}
    for k,v in pairs:
        if k in out:raise ValueError('duplicate key: '+repr(k))
        out[k]=v
    return out
def invalid_constant(v):raise ValueError('nonstandard constant: '+v)
def convert(source,target,limit):
    with Path(source).open('rb') as f:raw=f.read(MAX_BYTES+1)
    if len(raw)>MAX_BYTES:raise ValueError('input exceeds demo byte policy')
    text=raw.decode('utf-8',errors='strict')
    peak=check_depth(text,limit) # Runs before the JSON decoder.
    rows=json.loads(text,object_pairs_hook=unique,parse_constant=invalid_constant)
    if not isinstance(rows,list):raise ValueError('expected record array')
    for row in rows:
        if not isinstance(row,dict) or set(row)!={'id','payload'} or not isinstance(row['id'],str):
            raise ValueError('expected id string and payload only')
        todo=[row['payload'],row['id']]
        while todo:
            v=todo.pop()
            if isinstance(v,dict):
                for key in v:key.encode('utf-8',errors='strict')
                todo.extend(v.values())
            elif isinstance(v,list):todo.extend(v)
            elif isinstance(v,str):v.encode('utf-8',errors='strict')
            else:raise ValueError('demo requires string leaves')
    encoded=[(r['id'],json.dumps(r['payload'],ensure_ascii=False,separators=(',',':'))) for r in rows]
    with Path(target).open('x',encoding='utf-8',newline='') as f:
        w=csv.writer(f);w.writerow(['id','payload_json']);w.writerows(encoded)
    return {'peak_depth':peak,'limit':limit,'records':len(rows),'input_bytes':len(raw)}
if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('source');p.add_argument('target');p.add_argument('--max-depth',type=int,default=3);a=p.parse_args()
    try:print(json.dumps(convert(a.source,a.target,a.max_depth)))
    except (ValueError,OSError,RecursionError) as e:p.exit(1,type(e).__name__+': '+str(e)+'\n')
