"""Validate rendered and Markdown JSON examples against the deployed image offline."""
import json,re
from pathlib import Path
import deploy
root=deploy.ROOT;repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
examples=[]
for row in json.loads((root/'document-validation/examples.json').read_text()):
 for value in row['examples']:examples.append(dict(source=row['scenario']+'_html',scenario=row['scenario'],value=value))
for name in ('FIGHT_R5_WEB_CONFIG.ko.md','FALL_R2_WEB_CONFIG.ko.md','FIGHT_R5_WEB_HANDOFF.md','FALL_R2_WEB_HANDOFF.md'):
 for block in re.findall(r'```json\s*\n(.*?)\n```',(repo/'docs/integration'/name).read_text(),flags=re.S):
  examples.append(dict(source=name,scenario='FIGHT' if name.startswith('FIGHT') else 'FALL',value=json.loads(block)))
check="""import json
from app.fall_runtime import FallSettings
from app.fight_runtime import FightSettings
from app.scenario_parameters import apply
rows=EXAMPLES
for row in rows:
 s=dict(fall=FallSettings.parse({'engine':'r2'}).settings_payload(),fight=FightSettings.parse({'engine':'r5'}).settings_payload())
 v=row['value'];req=v if 'scenarioCode' in v else dict(scenarioCode=row['scenario'],enabled=True,parameters=v)
 apply(s,req)
 field=row['scenario'].lower();assert s[field]['engine']==('r2' if field=='fall' else 'r5')
print(json.dumps(dict(status='PASS',examples=len(rows))))
""".replace('EXAMPLES',repr(examples))
code="""import sys,json
from pathlib import Path
sys.path.insert(0,ROOT)
from install import FallR2Installer
i=FallR2Installer(ROOT,'icerti-ai2');built=json.loads((Path(ROOT)/'built.json').read_text())
out=i.cpu_job('ct-fall-r2-doc-examples',built['image'],['-c',CHECK],60)
i.fp.atomic(Path(ROOT)/'doc-examples.json',out);print(out.decode())
""".replace('ROOT',repr(deploy.REMOTE)).replace('CHECK',repr(check))
out=deploy.r.python(code,sudo=True,timeout=75)
(root/'document-validation/doc-examples.json').write_bytes(out)
print(out.decode())
