#!/usr/bin/env python3

import sys
from pathlib import Path
from ruamel.yaml import YAML
from ansi2html import Ansi2HTMLConverter

from rougail import Rougail
from rougail.config import get_rougail_config
from rougail.output_exporter import RougailOutputExporter
from rougail.user_data_file import RougailUserDataFile
from rougail.output_doc import RougailOutputDoc


if __name__ == "__main__":
    version = sys.argv[1]
#    rougailconfig = RougailConfig.copy()
    rougailconfig = get_rougail_config(backward_compatibility=False, add_extra_options=False)
    rougailconfig['main_dictionaries'] = ['firefox']
    rougailconfig['default_dictionary_format_version'] = version
    if Path('config/namespace').is_file():
        has_namespace = True
        has_foxyproxy = False
    elif Path('foxyproxy').is_dir():
        has_foxyproxy = True
        has_namespace = True
        rougailconfig['main_namespace'] = 'Firefox'
        rougailconfig['extra_dictionaries'] = {'FoxyProxy': ['foxyproxy']}
    else:
        has_foxyproxy = False
        has_namespace = False
        rougailconfig['main_namespace'] = None
#    rougailconfig['tiramisu_cache'] = "cache.py"
#    rougail = Rougail(rougailconfig)
#    config = rougail.get_config()
#    print(config.value.get())
    rougailconfig['step.output'] = 'doc'
    rougailconfig['doc.output_format'] = 'github'
    rougailconfig['doc.title_level'] = 3
    if Path('mode').is_file():
        rougailconfig['modes_level'] = ['basic', 'standard', 'advanced']
        has_mode = True
    else:
        has_mode = False
    inventory = RougailOutputDoc(rougailconfig=rougailconfig.copy())
    rougailconfig['step.output'] = 'exporter'
    header = inventory.formater.header()
    summary = Path('summary_before.md')
    if summary.is_file():
        with summary.open('r') as sfh:
            doc = sfh.read() + '\n\n'
    else:
        doc = ''
    yaml = YAML()
    namespace = 'firefox'
    file_found = False
    if rougailconfig['main_namespace']:
        all_dirs = [[rougailconfig['main_dictionaries']], rougailconfig['extra_dictionaries'].values()]
    else:
        all_dirs = [[rougailconfig['main_dictionaries']]]

    doc += inventory.formater.title('Screenshot', 2) + '\n'
    doc += f'<img src="{namespace}.png" width=50% height=50% alt="{namespace.capitalize()} Proxy setting"/>\n\n'
#    with doc_file.open('r') as docfh:
#        doc += docfh.read()
    doc += '\n' + inventory.formater.title('Structure', 2) + '\n'
    for r in all_dirs:
        for dirs in r:
            for d in dirs:
                files = list(Path(d).iterdir())
                files.sort()
                for f in files:
                    namespace = f.parent.name
                    file_found = True
                    if f.name.endswith('.yml') or f.name.endswith('.yaml'):
                        doc += inventory.formater.title(str(f), 3)
                        doc += '\n```yml\n'
                        with f.open(encoding="utf8") as file_fh:
                            doc += file_fh.read()
                        doc += '\n```\n'
    inv_doc = inventory.gen_doc()
    if file_found and inv_doc:
        doc += inventory.formater.title('Generated documentation', 3)
        CMD = f"foo@bar:~$ rougail -v {version} -m firefox/ "
        if has_namespace:
            CMD += "-s Firefox "
        if has_foxyproxy:
            CMD += "-xn FoxyProxy -xd 0 foxyproxy/ "
        if has_mode:
            CMD += "--modes_level basic standard advanced "
        cmd = CMD + "-o doc -do github"
        doc += f'```console\n{cmd}\n```\n'
        doc += inv_doc
    #
    config = Path('config')
    if config.is_dir():
        doc += inventory.formater.title('User data', 2)
        configs = list(config.iterdir())
        configs.sort()
        for idx, dirname in enumerate(configs):
            if dirname.is_file():
                continue
            for filename in dirname.iterdir():
                if filename.name.endswith('.yml') or filename.name.endswith('.yaml'):
                    doc += inventory.formater.title(f'Example {idx + 1}', 3)
                    doc += inventory.formater.title(str(filename), 4)
                    doc += '\n```yml\n'
                    with filename.open(encoding="utf8") as file_fh:
                        doc += file_fh.read()
                    doc += '\n```\n'
#                    with filename.open(encoding="utf8") as file_fh:
#                        objects = yaml.load(file_fh)
#                    doc += inventory.formater.yaml(objects)
                    #readme = dirname / 'README.md'
                    #if readme.is_file():
                    #    doc += inventory.formater.title('Description', 4)
                    #    with readme.open() as fh:
                    #        doc += fh.read() + '\n\n'
                    rougail = Rougail(rougailconfig)
                    tiramisu_config = rougail.get_config()
                    rougailconfig['step.user_data'] = ['file']
                    rougailconfig['file.filename'] = [str(filename.absolute())]
                    data = RougailUserDataFile(tiramisu_config, rougailconfig=rougailconfig)
                    ret = data.run()
                    errors = rougail.user_datas(ret)
                    export = RougailOutputExporter(tiramisu_config,
                                                   rougailconfig=rougailconfig,
                                                   user_data_errors=errors['errors'],
                                                   user_data_warnings=errors['warnings'],
                                                   )
                    export.exporter()
                    with export.formater.console.capture() as capture:
                        export.print()
                    conv = Ansi2HTMLConverter(inline=True)
                    doc += inventory.formater.title('Output', 4)
                    cmd = CMD + f"-u file -ff {filename}"
                    doc += f"```console\n{cmd}\n```\n"
                    conv_data = '<pre>' + conv.convert(capture.get(), full=False) + "</pre>\n"
                    doc += conv_data
                    with open(dirname / 'output_ro.html', 'w') as fh_output:
                        fh_output.write(conv_data)
                    if (config / 'read_write').is_file():
                        rougailconfig['exporter.read_write'] = True
                        export = RougailOutputExporter(tiramisu_config,
                                                       rougailconfig=rougailconfig,
                                                       user_data_errors=data.errors,
                                                       user_data_warnings=data.warnings,
                                                       )
                        export.exporter()
                        with export.formater.console.capture() as capture:
                            export.print()
                        conv = Ansi2HTMLConverter(inline=True)
                        doc += inventory.formater.title('Output in read write mode', 4)
                        cmd = cmd + " --exporter.read_write"
                        doc += f"```console\n{cmd}\n```\n"
                        conv_data = '<pre>' + conv.convert(capture.get(), full=False) + "</pre>\n"
                        doc += '<pre>' + conv_data + "</pre>\n"
                        with open(dirname / 'output_rw.html', 'w') as fh_output:
                            fh_output.write(conv_data)
    #
    summary = Path('summary_after.md')
    if summary.is_file():
        with summary.open('r') as sfh:
            doc += '\n\n' + sfh.read()
    #
    doc_file = Path('README.md')
    with doc_file.open('w') as docfh:
        docfh.write(doc)
    with doc_file.open('w') as docfh:
        docfh.write(doc)
