#!/usr/bin/env python3

import sys
import json

from collections import defaultdict


class ExpandShareds:
    class Shared:
        def __init__(self):
            self._shared_modules = None
            self.places_used = []

        def set_shared_modules(self, m):
            if self._shared_modules is not None:
                raise Exception()
            self._shared_modules = m

        def fill(self):
            if len(self.places_used) < 2 or self._shared_modules is None:
                raise Exception()
            for p in self.places_used:
                p.update(self._shared_modules)

    def __init__(self, root):
        self._shareds = defaultdict(self.Shared)
        self._collect_shareds(root)
        for s in self._shareds.values():
            s.fill()

    def _collect_shareds(self, node):
        if isinstance(node, dict):
            for x in node.values():
                self._collect_shareds(x)
            shared = node.pop('shared', None)
            if shared is not None:
                shared_uuid = shared.pop('uuid')
                self._shareds[shared_uuid].places_used.append(node)
                if len(shared) == 1:
                    self._shareds[shared_uuid].set_shared_modules(shared)
                elif len(shared):
                    raise Exception()
        if isinstance(node, list):
            for x in node:
                self._collect_shareds(x)


for fname in sys.argv[1:]:
    with open(fname) as f:
        j = json.load(f)
    ExpandShareds(j)
    with open(fname, 'w') as f:
        json.dump(j, f, sort_keys=True, indent=2)

