# Copyright 2026 Acute Technology Inc. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
"""Data Generator Counter Controller Class."""

from typing import TYPE_CHECKING, ClassVar

from aqpxlib.abstract import PxAbstractController
from aqpxlib.message import DataGeneratorCounterConfig as PxDataGeneratorCounterConfig

if TYPE_CHECKING:
    from aqpxlib.toplevel import AqProtocolExerciser


class PxDataGeneratorCounter(PxAbstractController):
    """A Data Generator counter controller device class.

    This class provides a high-level interface to a counter device on the
    Data Generator bus. It does not automatically create an actual instance
    on the Protocol Exerciser until the user calls the ``attach_to_bus`` method.

    Typical usage example:

    ```python
    dg_bus = PxDataGeneratorBus(exerciser, ch0=0, ch1=1)
    counter = PxDataGeneratorCounter(exerciser)
    counter.attach_to_bus(dg_bus)

    ... # Do any operation from this counter

    counter.detach_from_bus()
    ```
    """

    # Used to identify the class
    identifier: str = "data_generator_counter"
    valid_buses: ClassVar[list[str]] = ["data_generator"]

    protobuf_key: str = "data_generator_counter"

    # No device events defined yet for the counter
    _protobuf_available_event_fields: ClassVar[list[str]] = []

    def __init__(
        self,
        exerciser: "AqProtocolExerciser",
        config: PxDataGeneratorCounterConfig | None = None,
        clk_div: int = 0,
        *args,
        **kwargs,
    ) -> None:
        """Initialize a Data Generator counter controller.

        Args:
            exerciser: An exerciser instance used to send requests to the server.
            config: Optional counter configuration. If not provided, defaults
                to enabled=1 with the given clk_div.
            clk_div: Clock divider value. Only used when config is not provided
                or when the provided config has clk_div=0.
            *args: Additional arguments.
            **kwargs: Additional keyword arguments.

        """
        if config is None:
            config = PxDataGeneratorCounterConfig(enabled=1, clk_div=clk_div)
        elif clk_div != 0 and config.clk_div == 0:
            config.clk_div = clk_div

        super().__init__(exerciser, config=config, *args, **kwargs)


__all__ = [
    "PxDataGeneratorCounter",
    "PxDataGeneratorCounterConfig",
]
