#!/usr/bin/env python3
"""Run the production attachment document-text command on synthetic XLSX files.
Usage: python3 prove.py CHECKOUT OUTPUT_DIRECTORY
No parser or provider is replaced. Output contains only synthetic workbook data.
"""
import datetime, hashlib, json, os, pathlib, subprocess, sys, zipfile
from xml.sax.saxutils import escape
checkout = pathlib.Path(sys.argv[1]).resolve()
out = pathlib.Path(sys.argv[2]).resolve() / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
out.mkdir(parents=True)
ns = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
rels = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
strings = ['Reserved', 'West Depot'] + [f'Reserved {i}' for i in range(2,10)] + ['East Depot']
parts = {
 '[Content_Types].xml': '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/></Types>',
 '_rels/.rels': f'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="root" Type="{rels}/officeDocument" Target="xl/workbook.xml"/></Relationships>',
 'xl/workbook.xml': f'<workbook xmlns="{ns}" xmlns:r="{rels}"><sheets><sheet name="Inventory" sheetId="1" r:id="sheet1"/></sheets></workbook>',
 'xl/_rels/workbook.xml.rels': f'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="sheet1" Type="{rels}/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="strings" Type="{rels}/sharedStrings" Target="sharedStrings.xml"/></Relationships>',
 'xl/sharedStrings.xml': f'<sst xmlns="{ns}" count="11" uniqueCount="11">' + ''.join('<si><t>'+escape(s)+'</t></si>' for s in strings) + '</sst>',
}
sha = subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
transcript = [f'T3 Code production attachment document-text extraction\nCommit: {sha}\nEnvironment: Linux x86_64; Node '+subprocess.check_output(['node','--version'],text=True).strip()+'\nNo model, mock, test runner, or copied database.\nShared string 1 = West Depot; shared string 10 = East Depot.\nWorksheet row 1 = Item / Location; row 2 = Widget / B2.\n']
results = {}
for name, value in [('control','10'),('split','1<![CDATA[0]]>'),('whitespace-first',' <![CDATA[10]]>')]:
    worksheet = f'<worksheet xmlns="{ns}"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Item</t></is></c><c r="B1" t="inlineStr"><is><t>Location</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>Widget</t></is></c><c r="B2" t="s"><v>{value}</v></c></row></sheetData></worksheet>'
    workbook = out / (name+'.xlsx')
    with zipfile.ZipFile(workbook,'w',zipfile.ZIP_DEFLATED) as z:
        for path, content in {**parts,'xl/worksheets/sheet1.xml':worksheet}.items():
            info = zipfile.ZipInfo(path, (2026,1,1,0,0,0)); info.compress_type = zipfile.ZIP_DEFLATED
            z.writestr(info,content)
    env = dict(os.environ, T3CODE_DEV_SEED='0')
    proc = subprocess.run(['node','apps/server/src/bin.ts','__document-text',str(workbook),'.xlsx'],cwd=checkout,env=env,text=True,capture_output=True,timeout=30)
    results[name] = {'exitCode':proc.returncode,'stdout':proc.stdout,'stderr':proc.stderr,'sha256':hashlib.sha256(workbook.read_bytes()).hexdigest()}
    (out/(name+'.txt')).write_text(proc.stdout)
    transcript += [f'=== {name}.xlsx ===\nB2 XML: <c r="B2" t="s"><v>{value}</v></c>\nSHA256: {results[name]["sha256"]}\n$ node apps/server/src/bin.ts __document-text {name}.xlsx .xlsx\nExit: {proc.returncode}\n--- stdout ---\n{proc.stdout}\n--- end stdout ---\n']
    if proc.stderr: transcript += ['--- stderr ---\n'+proc.stderr]
text = '\n'.join(transcript)
(out/'transcript.txt').write_text(text)
(out/'results.json').write_text(json.dumps({'commit':sha,'results':results},indent=2))
print(text)
print('RESULT_DIRECTORY='+str(out),file=sys.stderr)
