import os
from pathlib import Path
from rougail import Rougail
from rougail.config import get_rougail_config
from rougail.output_doc import RougailOutputDoc

os.environ['COLUMNS'] = '80'

EXT = {'github': 'md', 'asciidoc': 'adoc', 'json': 'json', 'console': 'sh', 'gitlab': 'gitlab.md', "html": "html"}


def _test_root(root, contents=None):
    test_dir = Path(__file__).resolve().parent
    rougailconfig = get_rougail_config(backward_compatibility=False)
    rougailconfig['step.output'] = 'doc'
    if contents:
        rougailconfig["doc.contents"] = [contents]
#    rougailconfig['tiramisu_cache'] = 'p.py'
    dirs = [str(test_dir / 'root')]
    rougailconfig['main_structural_directories'] = dirs
    rougail = Rougail(rougailconfig)
    config = rougail.run()
    rougailconfig['doc.root'] = root
    if contents == 'changelog':
        rougailconfig["doc.previous_json_file"] = str(test_dir / "empty/out.json")
    for output_format, ext in EXT.items():
        if output_format == 'json' and contents:
            continue
        rougailconfig['doc.output_format'] = output_format
        inventory = RougailOutputDoc(config, rougailconfig=rougailconfig)
        doc = inventory.run()[1]
        if contents:
            result_file = test_dir / f'root_{root}_{contents}.{ext}'
        else:
            result_file = test_dir / f'root_{root}.{ext}'
        if not result_file.is_file():
            with open(str(result_file), 'w') as docfh:
                docfh.write(doc)
        with open(str(result_file)) as docfh:
            result = docfh.read()
        assert doc == result, result_file


def test_root():
    _test_root('a_family')


def test_root_sub():
    _test_root('a_family.an_other_family')


def test_root_changelog():
    _test_root('a_family', "changelog")


def test_root_sub_changelog():
    _test_root('a_family.an_other_family', "changelog")


def test_root_example():
    _test_root('a_family', "example")


def test_root_sub_example():
    _test_root('a_family.an_other_family', "example")
