"""Single-qubit depolarizing noise implementation.

This module provides depolarizing noise models for single-qubit operations,
applying random Pauli errors (X, Y, Z) to individual qubits with equal
probability during quantum gate operations.
"""

# Copyright 2023 The PECOS Developers
#
# 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
#
#     https://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 pecos as pc
from pecos.reps.pyphir.op_types import QOp


def noise_sq_depolarizing(op: QOp, p: float, noise_dict: dict) -> list[QOp] | None:
    """Apply single-qubit depolarizing noise to quantum operation.

    Applies depolarizing noise to each qubit in the operation independently
    based on the provided noise probability and noise model dictionary.

    Args:
        op: Quantum operation to apply noise to.
        p: Probability of noise occurring on each qubit.
        noise_dict: Dictionary mapping fault types to their probabilities.

    Returns:
        List of quantum operations including original operation and noise,
        or None if no noise is applied.
    """
    # Use fused operation to check and get error indices in one pass
    error_indices = pc.random.compare_indices(len(op.args), p)

    noise = {}
    if error_indices:
        for idx in error_indices:
            loc = op.args[idx]
            rand = pc.random.random(1)[0]
            p_tot = 0.0
            for fault1, prob in noise_dict.items():
                p_tot += prob

                if p_tot >= rand:
                    noise.setdefault(fault1, []).append(loc)
                    break

    if noise:
        buffered_ops = []

        if noise:
            for sym, args in noise.items():
                buffered_ops.extend((op, QOp(name=sym, args=args, metadata={})))

        else:
            buffered_ops.append(op)

        return buffered_ops

    return None
