from pytest import fixture  # , raises
import os
from pathlib import Path
from rougail import Rougail, RougailConfig
from rougail.output_doc import RougailOutputDoc

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

test_ok = sorted(list((Path(__file__).parent / 'changelog').iterdir()))
# test_ok = [Path(__file__).parent / 'changelog' / '10mod_variable_description']

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

def idfn(fixture_value):
    return fixture_value.name


@fixture(scope="module", params=test_ok, ids=idfn)
def test_dir(request):
    return request.param


def test_changelog(test_dir):
    rougailconfig = RougailConfig.copy()
    rougailconfig['main_namespace'] = None
    rougailconfig["step.output"] = "doc"
    rougailconfig['main_structural_directories'] = [str(test_dir / "before" / "rougail" / "00-base.yml")]
    rougailconfig["doc.output_format"] = "json"
    eolobj = Rougail(rougailconfig=rougailconfig)
    config = eolobj.run()
    generated_output = RougailOutputDoc(config, rougailconfig=rougailconfig).run()[1]
    destfile = Path('before.json')
    with destfile.open('w+') as fh:
        fh.write(generated_output)
    rougailconfig = RougailConfig.copy()
    rougailconfig['main_namespace'] = None
    rougailconfig["step.output"] = "doc"
    rougailconfig['main_structural_directories'] = [str(test_dir / "after" / "rougail" / "00-base.yml")]
    rougailconfig["doc.contents"] = ["changelog"]
    rougailconfig["doc.previous_json_file"] = str(destfile)
    eolobj = Rougail(rougailconfig=rougailconfig)
    config = eolobj.run()
    for output_format, ext in EXT.items():
        if output_format == 'json':
            continue
        rougailconfig["doc.output_format"] = output_format
        result = RougailOutputDoc(config, rougailconfig=rougailconfig).run()[1]
        output_file = test_dir / f'result.{ext}'
        if not output_file.is_file():
            with output_file.open('w') as outfh:
                outfh.write(result)
        with output_file.open() as outfh:
             attented_output = outfh.read()
        assert result == attented_output, f'filename {output_file}'
    #
    destfile.unlink()
