# python3 mkdata.py [outdir]  — از out/<lc>/{user,public}.docx و *.txt فایل‌های contract-data/ را می‌سازد
import zipfile, base64, hashlib, zlib, os, sys, glob
VERSION = '1.1'
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, 'out', 'contract-data')
os.makedirs(OUT, exist_ok=True)
def zr(p):
    a = zipfile.ZipFile(p); return {n: a.read(n) for n in a.namelist() if not n.endswith('/')}
def pack(b):
    c = zlib.compressobj(9, zlib.DEFLATED, -15); r = c.compress(b) + c.flush()
    return base64.b64encode(r).decode('ascii')
def rt(p): return open(p, encoding='utf8').read()
base = zr(os.path.join(HERE, 'out/fa/user.docx'))
OV = ['word/document.xml', 'word/footer1.xml', 'word/header1.xml', 'word/styles.xml']
order = ['[Content_Types].xml', '_rels/.rels']
names = order + [n for n in base if n not in order]
langs = ['fa'] + sorted(d for d in os.listdir(os.path.join(HERE, 'out')) if len(d) == 2 and d != 'fa')
def w(name, body):
    open(os.path.join(OUT, name), 'w', encoding='utf8').write(body)
sh = ['<?php', '// تولیدشده — بخش‌های مشترک قالب Word. دستی ویرایش نکنید.', 'return [']
for n in names:
    if n in ('word/document.xml', 'word/footer1.xml', 'word/header1.xml'): continue
    assert "'" not in n
    sh.append("    '%s' => '%s'," % (n, pack(base[n])))
sh += ['];']
w('shared.php', '\n'.join(sh) + '\n')
# styles.xml مشترک فقط برای fa؛ زبان‌های دیگر خودشان styles دارند — fa هم در variant می‌آید
plain_fa = rt(os.path.join(HERE, 'out/fa/user.txt'))
h = hashlib.sha256((VERSION + '\n' + plain_fa).encode('utf8')).hexdigest()
w('meta.php', "<?php\n// تولیدشده — نسخه و هش قرارداد (هش = sha256 از «نسخه + \\n + متن فارسی»)\nreturn ['version' => '%s', 'hash' => '%s', 'langs' => [%s]];\n" % (VERSION, h, ', '.join("'%s'" % l for l in langs)))
for lc in langs:
    o = ['<?php', '// تولیدشده — قرارداد به زبان %s. دستی ویرایش نکنید.' % lc, 'return [']
    for v in ('user', 'public'):
        d = zr(os.path.join(HERE, 'out', lc, v + '.docx'))
        o.append("    '%s' => [" % v)
        for n in OV: o.append("        '%s' => '%s'," % (n, pack(d[n])))
        o.append('    ],')
    o.append("    'text' => [")
    for v in ('user', 'public'):
        o.append("        '%s' => '%s'," % (v, pack(open(os.path.join(HERE, 'out', lc, v + '.txt'), 'rb').read())))
    o.append('    ],'); o.append('];')
    w(lc + '.php', '\n'.join(o) + '\n')
print('version', VERSION, 'hash', h, 'langs', len(langs))
