#!/bin/env python3

import sys, json

with open(sys.argv[1], 'r') if sys.argv[1] != "-" else sys.stdin as f:
    api_source = f.read()

api = json.loads(api_source)

def to_lua_type_annot(typedesc):
    if type(typedesc) is dict:
        return r'{ %s }' % ','.join('%s: %s' % (f["name"], to_lua_type_annot(f["type"])) for f in typedesc["fields"])
    basetype = typedesc.rsplit(' *', 1)[0]
    if typedesc == "char *":
        return "string"
    elif basetype == "float":
        return "number"
    elif basetype == "bool":
        return "boolean"
    elif basetype == "Control":
        return "Control"
    elif basetype == "Vec2":
        return r"{ x: number, y: number }"
    elif basetype == "Vec3":
        return r"{ x: number, y: number, z: number }"
    elif basetype == "Color":
        return r"{ r: number, g: number, b: number, a: number }"
    elif basetype == "Rect":
        return r"{ x: number, y: number, w: number, h: number }"
    else:
        return "unknown"
        # raise BaseException("Unhandled type for annotation: %s" % typedesc)

print("error(\"townengine lua api file is not supposed to be imported!\")")

type_annotations = {}
type_annotations["ctx"] = r"{ %s, udata: table }" % \
    ', '.join("%s: %s" % (f["name"], to_lua_type_annot(f["type"])) for f in api["types"]["Context"]["fields"])

for annot in type_annotations:
    print("---@type " + type_annotations[annot])
    print(r"%s = nil" % annot)

procedure_annotations = {}
for procedure, procedure_desc in api["procedures"].items():
    procedure_annotations[procedure] = {}
    procedure_annotations[procedure]["params"] = r"{ %s }" % \
        ', '.join("%s: %s" % (p["name"], to_lua_type_annot(p["type"]) + '?' * ("default" in p)) for p in procedure_desc["params"])
    if "return" in procedure_desc:
        procedure_annotations[procedure]["return"] = to_lua_type_annot(procedure_desc["return"])

for annot in procedure_annotations:
    print("---@param args " + procedure_annotations[annot]["params"])
    if "return" in procedure_annotations[annot]:
        print("---@return " + procedure_annotations[annot]["return"])
    print("function %s(args) end" % annot)
