import os
import sys
import pytest
from pathlib import Path
from cocotb.runner import get_runner, Simulator

sim = os.getenv('SIM', 'ghdl')
toplevel = os.getenv('TEST_TOP')
sim_args = ["--wave=wave.ghw", "--ieee-asserts=disable"]
extra_args = ["--std=08", "--ieee=synopsys", "-frelaxed-rules", "-P/unisim", "-Pmoku"]
extra_env = {"COCOTB_RESOLVE_X": "ZEROS", "COCOTB_REDUCED_LOG_FMT": "1"}

generics = os.getenv('TEST_GENERICS')
if generics:
    build_generics = dict(x.split('=') for x in generics.split(' '))
else:
    build_generics = []


@pytest.fixture(scope="module")
def runner() -> Simulator:
    build_dir = '.'

    vhdl_sources = list(Path().glob('*.vhd'))
    vhdl_sources += list((Path('support-vhdl')).glob('*.vhd'))

    # lib_vhdl_sources = list((this_dir / 'lib/hdl/moku').glob('*.vhd'))

    runner = get_runner(sim)

    # runner.build(
    #     hdl_library='moku',
    #     vhdl_sources=lib_vhdl_sources,
    #     build_args=extra_args,
    #     build_dir=build_dir)

    runner.build(
        hdl_library='work',
        vhdl_sources=vhdl_sources,
        hdl_toplevel=toplevel,
        build_args=extra_args,
        parameters=build_generics,
        build_dir=build_dir)

    runner.test_args = extra_args

    return runner


def test_bench(runner: Simulator):
    runner.test(
        hdl_toplevel=toplevel,
        hdl_toplevel_library="work",
        test_module='startup',
        plusargs=sim_args,
        waves=True,
        extra_env=extra_env,
    )
