import argparse
import os
import re
import sys


def _write_output(filename, content):
  if os.path.exists(filename):
    with open(filename, 'rt') as strm:
      orig_content = strm.read()

    if orig_content == content:
      return False

  dirpath = os.path.dirname(filename)
  if not os.path.isdir(dirpath):
    os.makedirs(dirpath)

  with open(filename, 'wt') as strm:
    strm.write(content)
    strm.flush()

  return True


def _main():
  parser = argparse.ArgumentParser()

  parser.add_argument(
      '--template-header-filepath', dest='template_header_filepath', required=True, type=str,
      help='Path to the template header, either absolute or relative to current working directory.')

  parser.add_argument(
      '--output-dirpath', dest='output_dirpath', required=True, type=str,
      help='Output directory path, either absolute or relative to the current working directory.')

  args = parser.parse_args()

  if not os.path.isabs(args.template_header_filepath):
    args.template_header_filepath = os.path.abspath(args.template_header_filepath)

  if not os.path.isabs(args.output_dirpath):
    args.output_dirpath = os.path.abspath(args.output_dirpath)

  header_content = [
    '// This file is automatically generated by scripts/generate_python_listener.py DO NOT EDIT!!!',
    '',
    '/*',
    ' Copyright 2019 Alain Dargelas',
    ' Licensed under the Apache License, Version 2.0 (the "License");',
    ' you may not use this file except in compliance with the License.',
    ' You may obtain a copy of the License at',
    '',
    '  http://www.apache.org/licenses/LICENSE-2.0',
    '',
    ' Unless required by applicable law or agreed to in writing, software',
    ' distributed under the License is distributed on an "AS IS" BASIS,',
    ' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
    ' See the License for the specific language governing permissions and',
    ' limitations under the License.',
    ' */',
    '',
    '#ifndef SURELOG_SV3_1APYTHONLISTENER_H',
    '#define SURELOG_SV3_1APYTHONLISTENER_H',
    '#pragma once',
    '',
    '#include <Surelog/API/PythonAPI.h>',
    '#include <Surelog/ErrorReporting/ErrorDefinition.h>',
    '#include <Surelog/ErrorReporting/Location.h>',
    '#include <parser/SV3_1aParserBaseListener.h>',
    '',
    'namespace SURELOG {',
    '',
    'class PythonListen;',
    '',
    'class SV3_1aPythonListener : public SV3_1aParserBaseListener {',
    'private:',
    '  PythonListen* m_pl = nullptr;',
    '  PyThreadState* m_interpState = nullptr;',
    '  antlr4::CommonTokenStream* m_tokens = nullptr;',
    '  uint32_t m_lineOffset = 0;',
    '',
    'public:',
    '  SV3_1aPythonListener(PythonListen* pf, PyThreadState* interpState, antlr4::CommonTokenStream* tokens, uint32_t lineOffset);',
    '  SV3_1aPythonListener(const SV3_1aPythonListener& orig);',
    '  ~SV3_1aPythonListener() override;',
    '',
    '  PyThreadState* getPyThreadState() { return m_interpState; }',
    '  PythonListen*  getPythonListen() { return m_pl; }',
    '  antlr4::CommonTokenStream* getTokenStream() { return m_tokens; }',
    '',
    '  void logError(ErrorDefinition::ErrorType error, antlr4::ParserRuleContext* ctx, std::string object, bool printColumn = false);',
    '  void logError(ErrorDefinition::ErrorType, Location& loc, bool showDuplicates = false);',
    '  void logError(ErrorDefinition::ErrorType, Location& loc, Location& extraLoc, bool showDuplicates = false);',
    '',
  ]
  script_content = [
    "'''",
    'This file is automatically generated by generate_python_listener_api.tcl DO NOT EDIT!!!',
    '',
    'Copyright 2019 Alain Dargelas',
    'Licensed under the Apache License, Version 2.0 (the \"License\");',
    'you may not use this file except in compliance with the License.',
    'You may obtain a copy of the License at',
    '',
    '  http://www.apache.org/licenses/LICENSE-2.0',
    '',
    'Unless required by applicable law or agreed to in writing, software',
    'distributed under the License is distributed on an \"AS IS\" BASIS,',
    'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
    'See the License for the specific language governing permissions and',
    'limitations under the License.',
    "'''",
    '',
    'trace = 1',
    ''
  ]

  found_first = False
  parse_method_name_regex = re.compile('virtual\s+void\s+(?P<method_name>(enter|exit|visit)\w+)\s*\(.+\)\s*override\s*\{\s*\}')
  with open(args.template_header_filepath, 'rt') as instrm:
    for line in instrm:
      line = line.strip()
      m = parse_method_name_regex.match(line)
      if m:
        found_first = True
        line = line.replace('virtual ', '')
        line = line.replace(' { }', '')
        line = line.replace('/*ctx*/', 'ctx')
        line = line.replace('/*node*/', 'node')

        method_name = m.group('method_name')
        arg3 = 'node' if 'Node *' in line else 'ctx'
        header_content.append('  ' + line + ' {')
        header_content.append(f'    PythonAPI::evalScript("{method_name}", this, (parser_rule_context *) {arg3});')
        header_content.append('  }')

        script_content.append(f'def {method_name}(prog, ctx):')
        if 'enter' in method_name:
          if method_name != 'enterEveryRule':
            script_content.extend([
              '  if trace:',
             f'    print("{method_name}")',
              '    print("  File: ", SLgetFile(prog, ctx), ", ", SLgetLine(prog, ctx))',
              '    text = SLgetText(prog, ctx)',
              '    print("  Text: ", text[:20], "...")'
            ])
        script_content.append('  pass')
        script_content.append('')
      elif not line and found_first:
        header_content.append('')

  header_content.extend([
    '};',
    '}  // namespace SURELOG',
    '',
    '#endif  /* SURELOG_SV3_1APYTHONLISTENER_H */',
    ''
  ])

  _write_output(os.path.join(args.output_dirpath, 'include', 'Surelog', 'API', 'SV3_1aPythonListener.h'), '\n'.join(header_content))
  _write_output(os.path.join(args.output_dirpath, 'src', 'API', 'slSV3_1aPythonListener.py'), '\n'.join(script_content))

  return 0


if __name__ == '__main__':
  sys.exit(_main())
