"""Add only defaulted R2 angle payloads; retain all existing engine/common values."""
from copy import deepcopy
import hashlib
import json
from pathlib import Path
import sys
import yaml


def migrate_spec(spec):
    from app.fall_r2.config import R2Config
    if type(spec) is not dict:raise ValueError('CONFIG_SPEC_REQUIRED')
    result=deepcopy(spec)
    if (spec.get('fall') or {}).get('engine')!='r2':return result
    result['fall']['r2']=R2Config.parse(spec['fall'].get('r2',{'schema_version':1})).payload()
    check=deepcopy(result);check['fall']=deepcopy(spec['fall'])
    assert check==spec
    return result


def migrate_document(value, kind):
    if kind=='template':return migrate_spec(value)
    key={'base':'streams','runtime':'added'}[kind]
    if type(value) is not dict or type(value.get(key)) is not list:raise ValueError('CONFIG_LIST_REQUIRED')
    result=deepcopy(value);result[key]=[migrate_spec(s) for s in value[key]]
    return result


def prepare(root):
    root=Path(root);out=root/'settings-after';out.mkdir(mode=0o700)
    changes=[]
    for entry in json.loads((root/'settings-inputs.json').read_text()):
        raw=(root/'settings-before'/entry['name']).read_bytes()
        assert hashlib.sha256(raw).hexdigest()==entry['before']
        old=json.loads(raw) if entry['format']=='json' else yaml.safe_load(raw)
        new=migrate_document(old,entry['kind'])
        assert migrate_document(new,entry['kind'])==new
        if old==new:encoded=raw
        elif entry['format']=='json':encoded=(json.dumps(new,indent=2,ensure_ascii=False)+'\n').encode()
        else:encoded=yaml.safe_dump(new,sort_keys=False,allow_unicode=True).encode()
        target=out/entry['name'];target.write_bytes(encoded);target.chmod(0o600)
        specs=[new] if entry['kind']=='template' else new[{'base':'streams','runtime':'added'}[entry['kind']]]
        changes.append(dict(entry,after=hashlib.sha256(encoded).hexdigest(),changed=raw!=encoded,count=len(specs),
                            r2_count=sum((s.get('fall') or {}).get('engine')=='r2' for s in specs)))
    (root/'settings-migration.json').write_text(json.dumps(changes,indent=2)+'\n')
    print(json.dumps({v['kind']:dict(count=v['count'],r2=v['r2_count'],changed=v['changed']) for v in changes}))


if __name__=='__main__':prepare(sys.argv[1])
