# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.

import pytest

from dynamo.sdk.core.protocol.interface import LinkedServices

pytestmark = pytest.mark.pre_merge


def test_remove_backend2():
    from dynamo.sdk.tests.pipeline import Backend, Backend2, Frontend, Middle

    # Initial state assertions
    assert set(Frontend.dependencies.keys()) == {"backend", "middle"}
    assert Frontend.dependencies["backend"].on == Backend
    assert Frontend.dependencies["middle"].on == Middle

    assert set(Middle.dependencies.keys()) == {"backend", "backend2"}
    assert Middle.dependencies["backend"].on == Backend
    assert Middle.dependencies["backend2"].on == Backend2

    assert Backend.dependencies == {}

    Frontend.link(Middle).link(Backend)
    LinkedServices.remove_unused_edges()

    # Final state assertions after linking and cleanup
    assert Frontend.dependencies["middle"].on == Middle
    assert set(Frontend.dependencies.keys()) == {"middle"}

    assert set(Middle.dependencies.keys()) == {"backend"}
    assert Middle.dependencies["backend"].on == Backend

    assert Backend.dependencies == {}
