# Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
#
# 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.

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import torch.fx
import torch
from torch.export import ExportedProgram

from tico.passes import ops
from tico.serialize.circle_mapping import extract_shape
from tico.utils import logging
from tico.utils.graph import create_node
from tico.utils.passes import PassBase, PassResult
from tico.utils.trace_decorators import trace_graph_diff_on_pass
from tico.utils.validate_args_kwargs import CopyArgs


@trace_graph_diff_on_pass
class LowerCopy(PassBase):
    """
    This pass lowers `aten.copy.default` to simpler broadcast operations.

    - If src and dst shapes are the same, the copy is redundant and folded away.
    - If src and dst shapes differ, it's replaced with expand (broadcast).

    This simplifies serialization by handling copy logic at the pass level.
    """

    def __init__(self):
        super().__init__()

    def call(self, exported_program: ExportedProgram) -> PassResult:
        logger = logging.getLogger(__name__)

        graph_module = exported_program.graph_module
        graph = graph_module.graph
        modified = False

        for node in graph.nodes:
            if not node.op == "call_function":
                continue

            if node.target != torch.ops.aten.copy.default:
                continue

            args = CopyArgs(*node.args, **node.kwargs)  # type: ignore[arg-type]
            dst = args.dst
            src = args.src

            dst_shape = list(extract_shape(dst))
            src_shape = list(extract_shape(src))

            # Case 1: Same shape - copy is redundant, just use src
            if dst_shape == src_shape:
                logger.debug(
                    f"{node.name}: Same shape {dst_shape}, replacing with src directly"
                )
                node.replace_all_uses_with(src, propagate_meta=False)
                modified = True
                continue

            # Case 2: Different shapes - need expand
            logger.debug(
                f"{node.name}: Different shapes src={src_shape} dst={dst_shape}, "
                f"inserting expand"
            )

            with graph.inserting_before(node):
                expand_node = create_node(
                    graph,
                    torch.ops.aten.expand.default,
                    args=(src, dst_shape),
                )

            node.replace_all_uses_with(expand_node, propagate_meta=True)
            modified = True

        graph.eliminate_dead_code()
        graph.lint()
        graph_module.recompile()

        return PassResult(modified)
