import gzip, csv, subprocess, random, json, sys
D7='/Users/apple/neerja/ceonline'
OUT='/Users/apple/neerja/ceonline-d10/archive/commerce-revisions'
def d7rows(sql):
    r=subprocess.run(['ddev','mysql','--batch','-e',sql],cwd=D7,capture_output=True,text=True)
    return r.stdout
checks=[('commerce_order_revision','revision_id'),
        ('commerce_payment_transaction_revision','revision_id'),
        ('field_revision_commerce_line_items','revision_id'),
        ('field_revision_commerce_order_total','revision_id')]
bad=0
for t,key in checks:
    # read a spread of rows out of the CSV
    with gzip.open(f'{OUT}/{t}.csv.gz','rt',newline='') as fh:
        rd=csv.reader(fh); hdr=next(rd); rows=list(rd)
    idx=hdr.index(key)
    sample=[rows[0], rows[len(rows)//2], rows[-1]]
    # longest `data` value we archived, if the table has one
    if 'data' in hdr:
        di=hdr.index('data')
        sample.append(max(rows,key=lambda r:len(r[di])))
    for row in sample:
        k=row[idx]
        raw=d7rows(f"SELECT * FROM `{t}` WHERE `{key}`={k}")
        lines=raw.rstrip('\n').split('\n')
        if len(lines)<2: print(f"  {t}: no D7 row for {key}={k}"); bad+=1; continue
        # decode D7 batch output the same way the exporter did
        def un(v):
            if v=='NULL': return ''
            o=[];i=0
            while i<len(v):
                c=v[i]
                if c=='\\' and i+1<len(v):
                    o.append({'t':'\t','n':'\n','0':'\0','\\':'\\'}.get(v[i+1],v[i+1])); i+=2
                else: o.append(c); i+=1
            return ''.join(o)
        d7=[un(f) for f in lines[1].split('\t')]
        if d7!=row:
            bad+=1
            print(f"  MISMATCH {t} {key}={k}")
            for h,a,b in zip(hdr,d7,row):
                if a!=b: print(f"     {h}: d7={a[:90]!r} csv={b[:90]!r}")
        else:
            note='' if 'data' not in hdr else f" (data {len(row[hdr.index('data')])} chars)"
            print(f"  ok {t:44} {key}={k}{note}")
print("\nvalue mismatches:", bad)
sys.exit(1 if bad else 0)
