"""
Module for drawing a dependency graph
"""

import tempfile

from dagon.db import Database, RunID

try:
    import graphviz
    HAVE_GRAPHVIZ = True
except ModuleNotFoundError as e:
    if e.name != 'graphviz':
        # pyright: reportConstantRedefinition=false
        HAVE_GRAPHVIZ = False
        raise
    # pyright: reportConstantRedefinition=false
    HAVE_GRAPHVIZ = False


def generate_graph(db: Database, run: RunID) -> str:
    tmpdir = tempfile.mkdtemp()
    dig = graphviz.Digraph(comment=f'Graph generated by Dagon for run {run}', directory=tmpdir)
    dig.attr(rankdir='LR', splines='spline')

    tasks = db(
        r'''
        SELECT DISTINCT dependent, end_state
          FROM dagon_task_deps_rel
    INNER JOIN dagon_tasks
            ON name = dependent
  NATURAL LEFT OUTER JOIN dagon_task_runs
         WHERE run_id=:r
        ''',
        r=run,
    )
    for tname, end_state in tasks:
        col = {
            'pending': 'cyan',
            'running': 'blue',
            'failed': 'red',
            'succeeded': 'green',
            'cancelled': 'orange',
            None: 'gray',  # No dagon_task_runs row for this target
        }[end_state]
        dig.node(tname, color=col, fontname='mono', penwidth='5', shape='rect')

    rows = db(r'''
        SELECT dep.dependent as target,
               dep.depends_on as dep,
               0
          FROM dagon_task_deps_rel dep
          JOIN dagon_tasks t
            ON t.name = dep.dependent
         WHERE run_id=:rid
      ORDER BY name
    ''',
              rid=run)

    for row in rows:
        out, in_, oo = row
        if in_ is None:
            continue
        style = 'dashed' if oo else 'solid'
        dig.edge(in_, out, style=style)

    dig.render(format='png', view=True)
    return str(dig)
