import json,re,time
from pathlib import Path
CAT=Path('C:/MCSJAgent/foster-workflow-catalog/catalog.json')
OUT=Path('C:/MCSJAgent/foster-workflow-catalog/recipes');OUT.mkdir(parents=True,exist_ok=True)
data=json.loads(CAT.read_text(encoding='utf-8')); made=[]
for x in data['items']:
    if not x.get('operational') or x.get('recipe_score',0)<5: continue
    src=next((Path(s) for s in x['sources'] if s.lower().endswith('.json')),None)
    if not src or not src.exists(): continue
    try:d=json.loads(src.read_text(encoding='utf-8'))
    except Exception:continue
    slug=re.sub(r'[^a-z0-9]+','-',x['title'].lower()).strip('-')[:80]
    nav=d.get('nav_step') or {}
    steps=[]
    if nav.get('heading') or nav.get('nav_path'): steps.append({'phase':'navigate','action':nav.get('heading','Open workflow'),'path':nav.get('nav_path',''),'note':nav.get('note','')})
    for card in d.get('card_steps',[]):
        steps.append({'phase':'operate','action':card.get('heading',''),'checks':card.get('checks',[])})
    recipe={'schema':'mcsj-recipe-v1','id':slug,'title':x['title'],'module':x['module'],'source':str(src).replace('\\','/'),'confidence':'source-compiled','timing_target_seconds':30,'requires_live_mapping':True,'short_answer':d.get('short_answer',''),'steps':steps,'watch_outs':d.get('watch_outs',[]),'completion_contract':['Use live chestervillagenydb only','Verify record/batch ID before write','Capture visible after-proof','For batches, Save alone is incomplete; verify and Update/Post when applicable']}
    path=OUT/(slug+'.json');path.write_text(json.dumps(recipe,indent=2),encoding='utf-8');made.append(str(path).replace('\\','/'))
idx={'generated_epoch':time.time(),'recipe_count':len(made),'recipes':made};(OUT/'index.json').write_text(json.dumps(idx,indent=2),encoding='utf-8')
print(json.dumps({'recipe_count':len(made),'sample':made[:15]},indent=2))
