""" Export configuration from DOC/DOCX documentation.

Requires Python >=3.8. """

from __future__ import annotations

try:
    from _version_ import __version__
except ImportError:
    __version__ = 'Development'

import sys
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import NoReturn

from processing import get_failures, process_files, search_directory
from logutil import *


def main() -> NoReturn:
    """ Entry point. """
    # (Actual main logic begins in _main; this is just an error handler)

    try:
        sys.exit(_main())
    except Exception:
        errmsg(f"*** Fatal error: ***")
        errexc()
        sys.exit(10)
    except KeyboardInterrupt:
        errmsg(f"*** Interrupted ***")
        sys.exit(2)

def _args() -> Namespace:
    parser = ArgumentParser(description="Export configuration from DOC/DOCX documentation",
        usage="%(prog)s [OPTIONS] <inputs ...> <output>",
        fromfile_prefix_chars='@')
    parser.add_argument('inputs', type=Path, help="files to process (can specify multiple)", nargs='+')
    parser.add_argument('output', type=Path, help="output directory; will be created if it does not exist")
    parser.add_argument('-v', '--verbose', action='store_true', help="enable more logging")
    parser.add_argument('-V', '--version', action='version', version=__version__, help="show script version and exit")
    parser.add_argument('-L', '--log', metavar='LOGFILE', type=Path, help="specify log file name or path", default='doc_file_processing.log')
    parser.add_argument('-P', '--noprogress', action='store_true', help="disable graphical progress bar")
    return parser.parse_args()

def _main() -> int:
    """ Main implementation. """

    # Get arguments
    args = _args()

    # Set up
    args.output.mkdir(parents=True, exist_ok=True)  # resolve() works better if the dir exists
    output_path: Path = args.output.resolve()
    input_paths: list[Path] = [path.resolve() for path in args.inputs]
    set_verbose(args.verbose)
    set_progress_enabled(not args.noprogress)

    # Open log file
    try:
        logfile = open(args.output / args.log, mode='w', encoding='utf-8')
        logfile.reconfigure(line_buffering=True)
    except Exception:
        set_logfile(None)
    else:
        set_logfile(logfile)

    progress_start()
    progress_title("Processing DOC/DOCX documentation")

    # Banner
    statusmsg("Starting doc file processing...", progress_major=True)
    contextmsg(f"  Script version {__version__}")
    contextmsg(f"  Python {sys.version}")

    # Enumerate directories
    input_paths = [f for path in input_paths for f in (search_directory(path) if path.is_dir() else [path])]

    # Run
    process_files(input_paths, output_path)

    progress_stop()

    # Report failures
    failures = get_failures()
    if failures:
        errmsg(f"*** {len(failures)} documents failed to export: ***")
        for path in failures:
            errmsg(f"  - {path}")
        return 1
    else:
        statusmsg(f"Done")
        return 0


# allow running this module directly
if __name__ == '__main__':
    main()
