#!/usr/bin/env python3
# SPDX-FileCopyrightText: © 2023 Christian BUHTZ <c.buhtz@posteo.jp>
#
# SPDX-License-Identifier: GPL-3.0-only
#
# This file is part of the program "Hyperorg" which is released under GNU
# General Public License v3 (GPLv3).
# See folder LICENSES or go to <https://www.gnu.org/licenses/#GPL>.
"""Entry point for the package"""
import sys
import pathlib
import logging
import locale
import argparse
import webbrowser
import hyperorg
from hyperorg.exporter import Exporter
from hyperorg.reader import Reader

_log = logging.getLogger(f'hyperog.{__name__}')


def logo_with_version():
    """Build ASCII-Art application name with version and git info.

    The use font name is 'Straight'."""

    ver = hyperorg.__version__
    git = hyperorg.get_git_string()

    logo = [
        r'  |__|     _   _  _  _   _  _',
        rf'  |  | \/ |_) (- |  (_) |  (_)  Version: {ver}',
        rf'       /  |                _/   {git}'
    ]

    return '\n'.join(logo)


def _extract_copyright() -> str:
    """Extract the SPDX copyright info from current file."""
    with pathlib.Path(__file__).open('r', encoding='utf-8') as handle:
        for line in handle:
            if 'SPDX-FileCopyrightText' in line:
                return line[line.index(':')+1:].strip()

    return '(ERROR unknown copyright)'


def init_argparse():
    """Define and parse commandline arguments.

    Defines the commandline arguments and options and parse the command line
    arguments.

    Returns:
       argparse.Namespaces: The parsed arguments in a dict like object.
    """
    app_full = hyperorg.get_full_application_string()
    author = hyperorg.meta['Author-email']
    prjurl = hyperorg.meta['Project-URL']['homepage']
    changelog = hyperorg.meta['Project-URL']['changelog']
    gpl = hyperorg.meta['License']
    copy = _extract_copyright()
    # REUSE-IgnoreStart
    epilog = f'{logo_with_version()}\n\n   Author : {author}' \
             f'\n  Project : {prjurl}\nChangelog : {changelog}\n' \
             f'  License : {gpl}\nCopyright : {copy}'
    # REUSE-IgnoreEnd

    parser = argparse.ArgumentParser(
        prog=app_full.split(' ', maxsplit=1)[0],
        description=hyperorg.meta['Summary'],
        epilog=epilog,
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('inputdir', type=pathlib.Path,
                        help='Source directory with org-files.')
    parser.add_argument('outputdir', type=pathlib.Path,
                        help='Destination directory for html-files.')
    parser.add_argument('--hardlinks', action='store_true',
                        help='Use hardlinks instead of symlinks for images '
                        'and other attachments in the input directory.')
    parser.add_argument('-s', '--show', action='store_true',
                        help='Open result in default browser.')
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='Give detailed information.')
    parser.add_argument('-d', '--debug', action='store_true',
                        help='Debug output.')
    parser.add_argument('--version', action='version', version=app_full)

    return parser.parse_args()


def main():
    """Main entry point"""
    # The interaction between locale and datetime seems a bit wired on the
    # first sight. As stated in the docu datetime use locale but the local
    # package not the OS locale.
    # The locale package itself doesn't use the OS locale for datetime things
    # by default (because of unittests).
    # This need to be activated explicit.
    locale.setlocale(locale.LC_TIME, '')

    args = init_argparse()
    hyperorg.init_logging(info=args.verbose, debug=args.debug)

    if args.debug is True:
        # Name, Version, As Root, OS
        for key, val in hyperorg.collect_minimal_diagnostics().items():
            _log.debug(f'{key}: {val}')

    reader = Reader(args.inputdir)
    node_count = reader.read_org_files()

    if node_count == 0:
        _log.warning('No nodes read. Stop here.')
        sys.exit(1)

    exporter = Exporter(args.outputdir, use_hardlinks=args.hardlinks)
    exporter.export_to_html()

    # Final message
    fp_indexhtml = pathlib.Path(args.outputdir) / 'index.html'
    if args.show:
        webbrowser.open_new_tab(str(fp_indexhtml))
    else:
        _log.info(f'To see the result open {fp_indexhtml}.')


if __name__ == '__main__':
    main()
