#!/usr/bin/env python3
"""C typedef structs -> PHP classes. Singletons (static props) for the VM globals, instance classes for the rest.
Usage: structs.py <c root> <out dir>"""
import re, sys, os

root, out = sys.argv[1], sys.argv[2]
headers = ['alis.h', 'image.h', 'audio/audio.h', 'channel.h', 'script.h', 'platform.h', 'sys/sys.h', 'screen.h', 'video/video.h']
SINGLETONS = {'sAlisVM': 'Alis', 'sImage': 'Img', 'sAudio': 'Aud', 'sScreen': 'Scr', 'sHost': 'Host'}
CLASSNAMES = {'sAlisScriptLive': 'ScriptLive', 'sAlisScriptData': 'ScriptData', 'sScriptHeader': 'ScriptHeader',
              'sSprite': 'Sprite', 'sPlatform': 'Platform', 'mouse_t': 'MouseT', 'pixelbuf_t': 'PixelBuf'}
SCALARS = {'u8', 's8', 'u16', 's16', 'u32', 's32', 's64', 'u64', 'int', 'char', 'float', 'double', 'bool', 'unsigned', 'long', 'short', 'size_t', 'time_t', 'intptr_t',
           'EPlatform', 'EPxFormat', 'EGame', 'eAlisState', 'EPalFormat', 'eChannelType', 'eAlisVideo'}

src = ''
for h in headers:
    p = os.path.join(root, h)
    if os.path.exists(p):
        src += open(p, encoding='utf-8', errors='replace').read() + '\n'
src = re.sub(r'/\*.*?\*/', '', src, flags=re.S)
src = re.sub(r'//[^\n]*', '', src)
src = src.replace('PACK_PUSH', '').replace('PACK_POP', '').replace('PACK_ATTR', '')

# find typedef struct { ... } Name;  (brace matching)
structs = {}
for m in re.finditer(r'typedef\s+(?:union|struct)\s*\w*\s*\{', src):
    i = m.end(); depth = 1
    while depth:
        if src[i] == '{': depth += 1
        elif src[i] == '}': depth -= 1
        i += 1
    body = src[m.end():i - 1]
    name = re.match(r'\s*(\w+)\s*;', src[i:])
    if name:
        structs[name.group(1)] = body

def consts(expr):
    known = {'kNameMaxLen': 16, 'kDescMaxLen': 1024, 'kPathMaxLen': 256, 'MAX_SCRIPTS': 512}
    for k, v in known.items():
        expr = expr.replace(k, str(v))
    try:
        return int(eval(expr, {}, {}))
    except Exception:
        return None

def fields(body):
    res = []
    # drop nested anonymous structs/unions, record them
    depth = 0; cur = ''; i = 0
    while i < len(body):
        c = body[i]
        if c == '{':
            depth += 1
        if depth == 0:
            cur += c
            if c == ';':
                res.append(cur.strip()); cur = ''
        else:
            if c == '}':
                depth -= 1
                if depth == 0:
                    j = body.index(';', i)
                    tail = body[i + 1:j].strip()
                    res.append('__nested__ ' + tail); cur = ''
                    i = j
        i += 1
    return res

def php_class(cname, body, static):
    kw = 'public static' if static else 'public'
    props, inits = [], []
    for f in fields(body):
        f = f.rstrip(';').strip()
        if not f:
            continue
        if f.startswith('__nested__'):
            tail = f[len('__nested__'):].strip()
            nm = re.match(r'(\w+)\s*(?:\[([^\]]+)\])?', tail)
            if not nm:
                continue
            n, arr = nm.group(1), nm.group(2)
            if arr:
                props.append(f'    /** nested C struct array, one array per element (keys = C field names) */\n    {kw} array ${n} = [];')
                inits.append((n, f'array_fill(0, {consts(arr)}, [])'))
            else:
                props.append(f'    /** nested C struct (keys = C field names) */\n    {kw} array ${n} = [];')
            continue
        f = re.sub(r'\bvolatile\b|\bconst\b|\bstruct\b|\bunsigned\b', '', f).strip()
        f = re.sub(r'\s*:\s*\d+\s*$', '', f)  # bit fields
        m = re.match(r'([A-Za-z_]\w*)\s*((?:\*\s*)*)(.*)$', f)
        if not m:
            continue
        ctype, ptr, rest = m.group(1), m.group(2).replace(' ', ''), m.group(3)
        for decl in rest.split(','):
            decl = decl.strip()
            d = re.match(r'((?:\*\s*)*)(\w+)\s*((?:\[[^\]]+\])*)', decl)
            if not d:
                continue
            p = ptr + d.group(1).replace(' ', '')
            n, dims = d.group(2), re.findall(r'\[([^\]]+)\]', d.group(3))
            comment = f'C: {ctype}{" " + p if p else ""} {n}' + ''.join(f'[{x}]' for x in dims)
            if dims:
                if ctype == 'char' and not p and len(dims) == 1:
                    props.append(f'    /** {comment} (C string) */\n    {kw} string ${n} = \'\';')
                    continue
                size = consts(dims[0])
                if ctype in SCALARS and not p:
                    fill = '0'
                    inits.append((n, f'array_fill(0, {size}, {fill})' if len(dims) == 1 else f'array_fill(0, {size}, array_fill(0, {consts(dims[1])}, 0))'))
                    props.append(f'    /** {comment} */\n    {kw} array ${n} = [];')
                else:
                    cls = CLASSNAMES.get(ctype, ctype)
                    if p:
                        props.append(f'    /** {comment}: array of ?{cls} (null = NULL) */\n    {kw} array ${n} = [];')
                        inits.append((n, f'array_fill(0, {size}, null)'))
                    else:
                        props.append(f'    /** {comment}: array of {cls} */\n    {kw} array ${n} = [];')
                        inits.append((n, f'array_map(fn () => new {cls}(), range(1, {size}))'))
                continue
            if p:
                if ctype in SCALARS or ctype == 'void':
                    props.append(f'    /** {comment}: address (int offset into Alis::$mem unless noted) */\n    {kw} int ${n} = 0;')
                elif ctype == 'FILE':
                    props.append(f'    /** {comment} */\n    {kw} mixed ${n} = null;')
                else:
                    cls = CLASSNAMES.get(ctype, ctype)
                    props.append(f'    /** {comment} */\n    {kw} ?{cls} ${n} = null;')
                continue
            if ctype in SCALARS:
                props.append(f'    /** {comment} */\n    {kw} int ${n} = 0;')
            elif ctype == 'jmp_buf':
                continue
            else:
                cls = CLASSNAMES.get(ctype, ctype)
                props.append(f'    /** {comment} */\n    {kw} {cls} ${n};')
                inits.append((n, f'new {cls}()'))
    lines = ['<?php', '', 'namespace App\\Alis;', '', f'/** Generated from the C struct of the same name (tools/structs.py), then edited by hand. */',
             f'final class {cname}', '{']
    lines += props
    if inits:
        lines.append('')
        if static:
            lines.append('    public static function init(): void')
            lines.append('    {')
            for n, e in inits:
                lines.append(f'        self::${n} = {e};')
        else:
            lines.append('    public function __construct()')
            lines.append('    {')
            for n, e in inits:
                lines.append(f'        $this->{n} = {e};')
        lines.append('    }')
    lines.append('}')
    return '\n'.join(lines) + '\n'

os.makedirs(out, exist_ok=True)
for sname, body in structs.items():
    if sname.startswith('sColor') or sname.startswith('sV6') or sname in ('sAlisOpcode', 'sAlisError', 'rect_t', 'sFliAudioChunk'):
        continue
    static = sname in SINGLETONS
    cname = SINGLETONS.get(sname) or CLASSNAMES.get(sname, sname)
    open(os.path.join(out, cname + '.php'), 'w').write(php_class(cname, body, static))
    print(sname, '->', cname)
