# -*- coding: utf-8 -*-
#
# Copyright 2018-2021- Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Renku rerun command."""

from renku.core.commands.graph import Graph
from renku.core.commands.update import execute_workflow
from renku.core.incubation.command import Command


def rerun_workflows():
    """Recreate files generated by a sequence of ``run`` commands."""
    return Command().command(_rerun_workflows).require_migration().require_clean().with_commit().require_nodejs()


def _rerun_workflows(client, revision, roots, siblings, inputs, paths):
    graph = Graph(client)
    outputs = graph.build(paths=paths, revision=revision)

    # Check or extend siblings of outputs.
    outputs = siblings(graph, outputs)
    output_paths = {node.path for node in outputs}

    # Normalize and check all starting paths.
    roots = {graph.normalize_path(root) for root in roots}
    output_paths -= roots
    outputs = [o for o in outputs if o.path not in roots]

    # Generate workflow and check inputs.
    # NOTE The workflow creation is done before opening a new file.
    workflow = inputs(client, graph.as_workflow(input_paths=roots, output_paths=output_paths, outputs=outputs))

    execute_workflow(
        client=client, workflow=workflow, output_paths=output_paths, command_name="rerun", update_commits=False
    )
