#!/usr/bin/python3

# SPDX-FileCopyrightText: 2025 Ämin Baumeler <amin@indyfac.ch>
#
# SPDX-License-Identifier: GPL-3.0-or-later

import sys
import numpy as np

if len(sys.argv) != 1:
    print(
        sys.argv[0]
        + """

Readh the superflow produced by `superflow` from stdin, and transform it to the
GraphViz dot language for graph visualization."""
    )
    sys.exit(1)


def print_superflow(n, adj):
    print("""digraph cluster_superflow {""")
    for v in range(max(n, 1)):
        print(f'SFN{v} [label="{v}"];')
    i = 0
    j = 1
    for entry in adj:
        if entry:
            print(f"SFN{j} -> SFN{i};")
        j = j + 1
        if i == j:
            j = j + 1
        if j >= n:
            i = i + 1
            j = 0
    print("}")


def print_subgraph(k, n, adj, labels):
    print("digraph cluster_G" + str(k) + " {")
    print('bgcolor="lightblue"')
    print('label="Causal Structure ' + str(k) + '"')
    print('node[shape="plain", fontsize="12pt"];')
    print('style="filled";')
    print('fillcolor="lightgrey";')
    for v in range(max(n, 1)):
        print(f'Gsc{k}N{v} [label="{labels[v]}"];')
    i = 0
    j = 1
    for entry in adj:
        if entry:
            print(f"Gsc{k}N{j} -> Gsc{k}N{i};")
        j = j + 1
        if i == j:
            j = j + 1
        if j >= n:
            i = i + 1
            j = 0
    print("}")


SF = None
i = 0
for line in sys.stdin:
    if not SF:
        SF = line
        adj = tuple(map(int, tuple(SF.strip())))
        n = int(np.ceil(np.sqrt(len(adj))))
        print_superflow(n, adj)
    else:
        labels, line = line.split(":")
        labels = tuple(map(int, tuple(labels)))
        adj = tuple(map(int, tuple(line.strip())))
        n = int(np.ceil(np.sqrt(len(adj))))
        print_subgraph(i, n, adj, labels)
        i = i + 1