# Copyright 2025 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.

"""Quantum state representation for Qulacs simulator.

This module provides quantum state representation and management for the Qulacs simulator, including state vector
storage and manipulation using a pure Rust backend for high performance and thread safety.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from pecos_rslib import simulators as rslib_sim

import pecos as pc
from pecos.simulators.qulacs import bindings
from pecos.simulators.sim_class_types import StateVector

if TYPE_CHECKING:
    from pecos import Array


class Qulacs(StateVector):
    """Wrapper of Qulacs state vector simulator using pure Rust backend."""

    def __init__(self, num_qubits: int, *, seed: int | None = None) -> None:
        """Initializes the state vector.

        Args:
            num_qubits (int): Number of qubits being represented.
            seed (int, optional): Random seed for deterministic behavior.
        """
        if not isinstance(num_qubits, int):
            msg = "``num_qubits`` should be of type ``int``."
            raise TypeError(msg)

        super().__init__()

        self.bindings = bindings.gate_dict
        self.num_qubits = num_qubits
        self.qulacs_state = rslib_sim.Qulacs(num_qubits, seed=seed)

        self.reset()

    def reset(self) -> Qulacs:
        """Reset the quantum state for another run without reinitializing."""
        # Initialize state vector to |0>
        self.qulacs_state.reset()
        return self

    @property
    def vector(self) -> Array:
        """Get the quantum state vector from Qulacs.

        Returns:
            The state vector as a PECOS array with complex values.
        """
        # Convert from [(real, imag), ...] tuples to complex array
        complex_tuples = self.qulacs_state.vector
        return pc.array(
            [complex(real, imag) for real, imag in complex_tuples],
            dtype="complex",
        )
