#!/usr/bin/env python3

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('statuscodes', help='path/to/Opc.Ua.NodeIds.csv')
parser.add_argument('outfile', help='outfile w/o extension')
parser.add_argument('namespace', help='NS0')
args = parser.parse_args()

rows = []
with open(args.statuscodes, encoding='utf-8-sig') as f:
    lines = f.readlines()
    for l in lines:
        l = l.strip()
        if not l:
            continue
        # Auto-detect separator: tab, semicolon, or comma
        if '\t' in l:
            parts = l.split('\t')
        elif ';' in l:
            parts = l.split(';')
        else:
            parts = l.split(',')
        if len(parts) < 3:
            continue
        name, nodeid, nodeclass = parts[0], parts[1], parts[2]
        # Handle CSVs where the first column is the numeric NodeId
        # (new format: NodeId, Name, NodeClass) vs traditional (Name, NodeId, NodeClass)
        if nodeid.isdigit():
            rows.append((name, nodeid, nodeclass))
        elif name.isdigit():
            rows.append((nodeid, name, nodeclass))
        else:
            # Skip header rows or other non-data lines
            continue

fh = open(args.outfile + ".h", "w", encoding='utf8')
def printh(string):
    print(string, end='\n', file=fh)

#########################
# Print the header file #
#########################

printh('''/**********************************
 * Autogenerated -- do not modify *
 **********************************/

#ifndef UA_NODEIDS_{0}_H_
#define UA_NODEIDS_{0}_H_

/**
 * Namespace Zero NodeIds
 * ----------------------
 * Numeric identifiers of standard-defined nodes in namespace zero. The
 * following definitions are autogenerated from a CSV file */
'''.format(args.namespace))

for row in rows:
    printh(f"#define UA_{args.namespace}ID_{row[0].upper()} {row[1]} /* {row[2]} */")

printh(f'''#endif /* UA_NODEIDS_{args.namespace}_H_ */ ''')

fh.close()
