from pathlib import Path

Import('env')
env = env.Clone()

# short colored build output, if the top-level pretty tool is present (main-repo build)
_pretty = Dir('#tools/scons/site_tools').File('pretty.py')
if not _pretty.exists():
  _pretty = Dir('#site_scons/site_tools').File('pretty.py')
if _pretty.exists():
  env.Tool('pretty', toolpath=[_pretty.dir.abspath])
if not hasattr(env, 'PrettyAction'):
  env.AddMethod(lambda e, cmd, label, **kw: Action(cmd), 'PrettyAction')

generator = File("generator/generator.py")

source_files = [
  File(str(f))
  for f in Path("generator").rglob("*")
  if f.is_file() and f.suffix in {".py", ".dbc"}
]

output_files = [
  f.name.replace(".dbc", "_generated.dbc")
  for f in Path("generator").rglob("*.dbc")
  if not f.name.startswith("_")
]

# include DBCs generated by python scripts
output_files += [
  f.name.replace(".py", "_generated.dbc")
  for f in Path("generator").rglob("*.py")
  if not f.name.startswith(("_", "test_")) and f.name != "generator.py"
]

generated = env.Command(
  target=list(set(output_files)),
  source=[generator] + source_files,
  action=env.PrettyAction("python3 ${SOURCES[0]}", 'GEN'),
)
