"""Core 0 DMA I2S Audio Synthesizer, ULP Coprocessor & CAN Bus Inspector.

Demonstrates Phase 4B & 4C hardware subsystems:
- Non-blocking Core 0 DMA 16-bit PCM audio streaming (`hal.audio_open` / `hal.audio_write`)
- ULP-RISC-V (ESP32-S3) / LP-Core (ESP32-C6) shared RTC memory (`hal.ulp_write_shared` / `ulp_read_shared`)
- Industrial CAN 2.0B / TWAI frame transmission & zero-copy receive (`hal.can_send` / `can_recv_into`)

Run locally:
    pylotos-sim examples/audio_synth_and_industrial.py --board m5stack_cores3 --port 8080
"""

import math
import struct

import hal
import pylotos.ui as ui

_can_rx = bytearray(8)
_pcm_buf = bytearray(640)  # 320 mono 16-bit samples = 20 ms @ 16 kHz

hal.audio_open(sample_rate=16000, channels=1, enable_rx=False, volume_pct=70)
hal.can_init(tx_gpio=2, rx_gpio=1, bitrate_bps=500000)
hal.ulp_write_shared(0, 1)

st = ui.State(
    freq_hz=440,
    volume=70,
    tones_played=0,
    ulp_counter=1,
    can_tx=0,
    last_can="(idle)",
)


def _play_chord():
    f = float(st.freq_hz)
    for i in range(320):
        sample = int(12000.0 * math.sin(2.0 * math.pi * f * (i / 16000.0)))
        struct.pack_into("<h", _pcm_buf, i * 2, sample)
    hal.audio_set_volume(int(st.volume))
    hal.audio_write(_pcm_buf)
    st.tones_played = st.tones_played + 1
    app.toast("DMA PCM burst @ {} Hz".format(int(f)))


def _step_ulp_and_can():
    nxt = hal.ulp_read_shared(0) + 1
    hal.ulp_write_shared(0, nxt)
    st.ulp_counter = hal.ulp_read_shared(0)

    payload = struct.pack(">II", st.ulp_counter, int(st.freq_hz))
    hal.can_send(0x123, payload)
    st.can_tx = st.can_tx + 1

    rx = hal.can_recv_into(_can_rx)
    if rx is not None:
        arb_id, dlc, _ext = rx
        st.last_can = "0x{:03X} [{}B]".format(arb_id, dlc)


app = ui.App(
    "Audio & CAN",
    state=st,
    screens=[
        ui.Screen(
            "DMA Audio",
            icon="play",
            children=[
                ui.Metric("PCM Bursts", st.bind("tones_played"), accent="cyan"),
                ui.Card(
                    "Core 0 I2S Synthesizer",
                    children=[
                        ui.Slider("Pitch", st.bind("freq_hz"), min=220, max=1760, step=55, unit="Hz"),
                        ui.Slider("Volume", st.bind("volume"), min=0, max=100, step=5, unit="%"),
                        ui.Button("Stream 20 ms Sine", on_click=_play_chord, shortcut="p"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "ULP & CAN",
            icon="cpu",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("ULP Reg[0]", st.bind("ulp_counter"), accent="gold"),
                        ui.Metric("CAN Frames", st.bind("can_tx"), accent="cyan"),
                    ],
                ),
                ui.Card(
                    "Industrial TWAI Bus",
                    children=[
                        ui.KeyValue("Last CAN RX", st.bind("last_can")),
                        ui.Button("Send CAN 0x123 + Step ULP", on_click=_step_ulp_and_can, shortcut="c"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.audio_close()
        hal.can_deinit()
