//! Clock tree initialization for {{ ir.board.name }}.
//!
//! Peripheral clock gating and reset on {{ ir.chip.name }} are controlled
//! by the Power, Reset and Clock Module (PRCM) — see TI SWCU185 §4. The
//! SimpleLink PRCM model differs from the Espressif SYSTEM / PCR block in
//! two ways called out by CHIPS-TI-00 §10.2:
//!
//! 1. PRCM CLKGR (run-mode), CLKGS (sleep-mode), CLKGDS (deep-sleep-mode)
//!    writes are **staged** — they do not take effect until software
//!    pulses `PRCM.CLKLOADCTL.LOAD` and polls `LOAD_DONE`.
//! 2. Peripheral resets live in dedicated per-class registers
//!    (`PRCM.RESETUART`, `PRCM.RESETI2C`, `PRCM.RESETGPIO`, etc.) and are
//!    asserted high / released by clearing.
//!
//! Bring-up order per used peripheral: enable CLKGR bit -> pulse
//! `CLKLOADCTL.LOAD` -> poll `CLKLOADCTL.LOAD_DONE` -> release reset.
//!
//! High-frequency SCLK_HF source selection (XOSC_HF / RCOSC_HF / TCXO) is
//! handled by the bootloader and AON oscillator state machine; this code
//! does not currently reprogram the CPU clock. See `board.rs` for the
//! constants.

use {{ ir.chip.pac_crate }} as pac;

/// Enable and reset every peripheral used by this board.
///
/// Called by [`crate::pac::init`] as the first bring-up step, before IOC
/// configuration so that peripheral registers are writable. Each used
/// peripheral's `prcm:` entry in `chipdb/rlvgl-chips-ti/db/chips/{{ chip_stem }}.yaml`
/// names the clock-gate register/field and the reset register/field;
/// fields are written via the svd2rust-shaped `{{ ir.chip.pac_crate }}` PAC.
pub fn init() {
    let p = unsafe { pac::Peripherals::steal() };
    {% for name in peripherals_used %}
    {% set gate = ir.chip.prcm[name] %}
    {% if gate %}
    // {{ name }} — clock enable {{ gate.clk_en_field }}{% if gate.clk_en_variant %}.{{ gate.clk_en_variant }}{% endif %} on {{ gate.clk_en_reg }},
    //             reset {{ gate.rst_field }} on {{ gate.rst_reg }}
    {% if gate.clk_en_variant -%}
    // `{{ gate.clk_en_field }}` is a multi-bit enum FieldWriter in this PAC
    // vintage; select the instance variant rather than calling `.set_bit()`.
    p.prcm.{{ gate.clk_en_reg | pac_path }}.modify(|_, w| w.{{ gate.clk_en_field }}().{{ gate.clk_en_variant }}());
    {%- else -%}
    p.prcm.{{ gate.clk_en_reg | pac_path }}.modify(|_, w| w.{{ gate.clk_en_field }}().set_bit());
    {%- endif %}
    // Stage the gate change: pulse CLKLOADCTL.LOAD and wait for LOAD_DONE.
    p.prcm.clkloadctl().modify(|_, w| w.load().set_bit());
    while p.prcm.clkloadctl().read().load_done().bit_is_clear() {}
    // Release the peripheral from reset (clear bit deasserts reset).
    p.prcm.{{ gate.rst_reg | pac_path }}.modify(|_, w| w.{{ gate.rst_field }}().clear_bit());
    {% else %}
    // {{ name }}: no prcm entry in chip IR (TODO — populate chipdb yaml)
    {% endif %}
    {% endfor %}
}
