"""Generate ISO_C_BINDING declarations from the repository C interfaces.

Run from any directory with Python 3. Generated files are checked in.
Pointers deliberately remain C_PTR, VALUE: use C_LOC on TARGET storage.
"""
from pathlib import Path
import re

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]

TYPES = '''  type, bind(C) :: GO64_StartInfo
    integer(c_int64_t) :: magic, argc
    type(c_ptr) :: argv
  end type
  type, bind(C) :: GO64_FSInfo
    integer(c_int64_t) :: id, parent_id, bytes, reference_count, metadata_count
    integer(c_int16_t) :: name(128), name_length
    integer(c_int8_t) :: is_directory
  end type
  type, bind(C) :: GO64_SocketAddress
    integer(c_int16_t) :: family, port
    integer(c_int8_t) :: address(4)
  end type
  type, bind(C) :: GO64_WindowOptions
    integer(c_int32_t) :: x, y, width, height, background
    character(kind=c_char) :: title(64)
  end type
  type, bind(C) :: GO64_Drawing
    integer(c_int32_t) :: x, y, width, height, color
    character(kind=c_char) :: text(128)
  end type
  type, bind(C) :: GO64_Blit
    integer(c_int32_t) :: x, y, width, height, stride, format
    type(c_ptr) :: pixels
  end type
  type, bind(C) :: GO64_Event
    integer(c_int32_t) :: type, x, y, width, height, buttons, key, modifiers
  end type
'''


def declaration(c_type):
    if '*' in c_type:
        return 'type(c_ptr)'
    return {'int64_t': 'integer(c_int64_t)', 'uint64_t': 'integer(c_int64_t)',
            'int32_t': 'integer(c_int32_t)', 'uint32_t': 'integer(c_int32_t)',
            'float': 'real(c_float)', 'double': 'real(c_double)'}[c_type.strip()]


def prototypes(text, prefix):
    return re.findall(r'(?:GO64_NORETURN\s+)?(int64_t|void\s*\*|void)\s+('
                      + prefix + r'\w+)\s*\(([^;{}]*?)\)\s*;', text, re.S)


def module(name, items, preamble='', used=''):
    lines = ['! Generated by bindings/fortran/generate.py. Do not edit.',
             f'module {name}', '  use iso_c_binding', used, '  implicit none', preamble,
             '  interface']
    for ret, symbol, args in items:
        params = []
        if args.strip() != 'void':
            for arg in args.split(','):
                match = re.fullmatch(r'\s*(.*?)\b(\w+)\s*', arg, re.S)
                if not match:
                    raise ValueError(arg)
                params.append((match[2], declaration(match[1])))
        kind = 'subroutine' if ret == 'void' else 'function'
        result = '' if ret == 'void' else ' result(r)'
        lines += [f'    {kind} {symbol}( &']
        if params:
            lines += ['      ' + param + ', &' for param, _ in params[:-1]]
            lines += ['      ' + params[-1][0] + f') bind(C, name="{symbol}"){result}']
        else:
            lines += [f'      ) bind(C, name="{symbol}"){result}']
        lines += ['      import']
        if ret != 'void':
            lines += ['      ' + declaration(ret) + ' :: r']
        lines += ['      ' + decl + ', value :: ' + param for param, decl in params]
        lines += [f'    end {kind} {symbol}']
    lines += ['  end interface', f'end module {name}', '']
    text = '\n'.join(line for line in lines if line is not None)
    if max(map(len, text.splitlines())) > 132:
        raise ValueError('Fortran line too long')
    (HERE / (name + '.f90')).write_text(text, encoding='utf-8')


def main():
    header = (ROOT / 'bindings/native/gaspardos_x64_syscall.h').read_text(encoding='utf-8')
    native = [item for item in prototypes(header, 'GO64_') if not item[1].startswith('GO64_asm_')]
    constants = []
    for name, value in re.findall(r'\b(GO64_\w+)\s*=\s*(\d+)', header):
        constants.append(f'  integer(c_int64_t), parameter :: {name} = {value}_c_int64_t')
    for name, value in re.findall(r'^#define (GO64_(?:SYS_\w+|BLIT_\w+))\s+(\d+)u?\s*$', header, re.M):
        constants.append(f'  integer(c_int64_t), parameter :: {name} = {value}_c_int64_t')
    constants += ["  integer(c_int64_t), parameter :: GO64_START_MAGIC = int(z'474F363441524753', c_int64_t)"]
    module('gaspardos_native', native, TYPES + '\n'.join(constants))
    bridge = prototypes((HERE / 'gui_bridge.h').read_text(encoding='utf-8'), 'gof_')
    module('gaspardos_gui', bridge, used='  use gaspardos_native')
    # Every public routine has one canonical C prototype for the site reference.
    page = ['# Fortran binding reference', '',
            'Generated from the native header and the C++ bridge header. Both modules use',
            '`iso_c_binding`. All pointer arguments are `type(c_ptr), value`:',
            'pass `c_loc(target)` or `c_null_ptr` only where the API allows it.',
            'All 64-bit integer arguments require `_c_int64_t` constants.', '',
            'C unsigned integers preserve their bits in signed Fortran integers.',
            'A native result below zero is a raw kernel error. Bridge Boolean results',
            'are 0/1; bridge validation failures are negative, allocation failure is -12.',
            'Pointer constructors return `c_null_ptr` on failure.', '',
            '[Français: guide](fr/fortran/api.md) · [English: guide](en/fortran/api.md)', '']
    for title, items in [('gaspardos_native', native), ('gaspardos_gui', bridge)]:
        page += ['## ' + title, '']
        generated = (HERE / (title + '.f90')).read_text(encoding='utf-8')
        for ret, symbol, args in items:
            interface = re.search(r'    (?:function|subroutine) ' + symbol +
                                  r'\(.*?    end (?:function|subroutine) ' + symbol,
                                  generated, re.S)[0]
            page += ['### ' + symbol, '', '```fortran',
                     '\n'.join(line[4:] for line in interface.splitlines()), '```', '',
                     'C ABI:', '', '```c', f'{ret} {symbol}({" ".join(args.split())});', '```', '']
    (ROOT / 'site/docs/fortran-reference.md').write_text('\n'.join(page), encoding='utf-8')
    print(f'Generated {len(native)} native and {len(bridge)} GUI/desktop/graphics interfaces.')


if __name__ == '__main__':
    main()
