# ========= Copyright 2026 @ Strukto.AI 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.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

from typing import Callable

from mirage.commands.builtin.generic.cp import cp as generic_cp
from mirage.commands.builtin.generic.cp import parse_cp_flags
from mirage.commands.builtin.generic.crossmount.types import CrossResult
from mirage.commands.builtin.generic.crossmount.utils import (
    flat_scopes, transfer_primitives)
from mirage.commands.spec import SPECS
from mirage.commands.spec.types import FlagValue, FlagView
from mirage.runtime.types import DispatchFn
from mirage.types import PathSpec, PrimitiveCopy


async def run_cp(
        scopes: list[PathSpec],
        flag_kwargs: dict[str, FlagValue],
        dispatch: DispatchFn,
        storage_key: Callable[[PathSpec], str] | None = None) -> CrossResult:
    """Copy operands that span mounts via the shared generic cp.

    Pure wiring: the generic runs in its primitive mode (no native copy),
    reading from the source mount and writing to the destination mount
    through dispatch-relayed primitives.

    Args:
        scopes (list[PathSpec]): Path operands in command-line order.
        flag_kwargs (dict): Flags parsed against the shared cp spec.
        dispatch (DispatchFn): Workspace operation dispatcher.
        storage_key (Callable | None): Maps an operand to its storage
            identity so two prefixes over one store compare equal.
    """
    fl = FlagView(flag_kwargs, spec=SPECS["cp"])
    primitives = transfer_primitives(dispatch)
    return await generic_cp(flat_scopes(scopes),
                            stat=primitives["stat"],
                            strategy=PrimitiveCopy(
                                read_bytes=primitives["read_bytes"],
                                write=primitives["write"],
                                mkdir=primitives["mkdir"],
                                readdir=primitives["readdir"]),
                            flags=parse_cp_flags(fl),
                            backend_key=storage_key)
