#!/usr/bin/env python3
# mypy: disallow-untyped-defs
# pylint: disable=C0112,C0114,C0115,C0116,C0209,C0301,R0903
# -*- Python -*- See copyright, etc below
######################################################################

import argparse
import re

#######################################################################


class VlSphinxExtract:
    debug = 0

    def process(self, filename: str) -> None:
        with open(filename, "r", encoding="utf8") as fhr:
            fhw = None
            for line in fhr:
                # =for VL_SPHINX_EXTRACT "file_to_write_to"
                match = re.search(r'VL_SPHINX_EXTRACT +"([^"]+)"', line)
                if match:
                    outname = match.group(1)
                    print("Writing %s" % outname)
                    fhw = open(outname, "w", encoding="utf8")  # pylint: disable=consider-using-with
                    fhw.write(".. comment: generated by vl_sphinx_extract from " + filename + "\n")
                    fhw.write(".. code-block::\n")
                elif re.match(r'^[=a-zA-Z0-9_]', line):
                    fhw = None
                elif fhw:
                    fhw.write(line)


#######################################################################

parser = argparse.ArgumentParser(
    allow_abbrev=False,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""Read a file and extract documentation data.""",
    epilog="""This program is free software; you can redistribute it and/or modify it
under the terms of either the GNU Lesser General Public License Version 3
or the Perl Artistic License Version 2.0.

SPDX-FileCopyrightText: 2021-2026 Wilson Snyder
SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0
""")

parser.add_argument('--debug', action='store_const', const=9, help='enable debug')
parser.add_argument('path', help='path to extract from')
Args = parser.parse_args()

o = VlSphinxExtract()
o.debug = Args.debug
o.process(Args.path)

######################################################################
# Local Variables:
# compile-command: "./vl_sphinx_extract --debug ../../bin/verilator"
# End:
