from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class UartTiming:
    baud: int = 38_400
    data_bits: int = 8
    parity_bits: int = 0
    stop_bits: int = 1
    start_bits: int = 1

    @property
    def bits_per_character(self) -> int:
        return self.start_bits + self.data_bits + self.parity_bits + self.stop_bits

    def seconds_per_character(self) -> float:
        return self.bits_per_character / max(1, self.baud)

    def micros_per_character(self) -> float:
        return 1_000_000.0 * self.seconds_per_character()

    def cycles_per_character(self, clock_hz: int) -> int:
        return max(1, round(max(1, clock_hz) * self.seconds_per_character()))

    def summary(self, clock_hz: int) -> str:
        return (
            f"uart_{self.data_bits}{'N' if self.parity_bits == 0 else 'P'}{self.stop_bits} "
            f"baud={self.baud} byte_us={self.micros_per_character():.3f} "
            f"byte_cycles={self.cycles_per_character(clock_hz)}"
        )


__all__ = ["UartTiming"]
