#include "hardware.h"
#include "app_config.h"
#include "main.h"
#include "stm32wbxx_nucleo.h"

/*
 * Markdown note:
 * - This file is the only place that should know real GPIO/ADC pins.
 * - Replace the weak placeholder code with HAL_GPIO_ReadPin() and HAL_ADC calls
 *   after STM32CubeWB/CubeMX generates the board initialization.
 */

void Hardware_Init(void)
{
    GPIO_InitTypeDef gpio = {0};

    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOE_CLK_ENABLE();

#if (APP_ROLE_DETECT_ENABLED != 0U)
    gpio.Pin = APP_ROLE_DETECT_GPIO_PIN;
    gpio.Mode = GPIO_MODE_INPUT;
    gpio.Pull = APP_ROLE_DETECT_PULL;
    gpio.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(APP_ROLE_DETECT_GPIO_PORT, &gpio);
#endif

    gpio.Pin = APP_BUTTON1_GPIO_PIN | APP_BUTTON2_GPIO_PIN | APP_BUTTON3_GPIO_PIN;
    gpio.Mode = GPIO_MODE_INPUT;
    gpio.Pull = (APP_BUTTON_ACTIVE_LEVEL == 0U) ? GPIO_PULLUP : GPIO_PULLDOWN;
    gpio.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(APP_BUTTON_GPIO_PORT, &gpio);

    gpio.Pin = APP_ROLE_LED_GPIO_PIN;
    gpio.Mode = GPIO_MODE_OUTPUT_PP;
    gpio.Pull = GPIO_NOPULL;
    gpio.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(APP_ROLE_LED_GPIO_PORT, &gpio);
    Hardware_SetRoleLed(false);
}

void Hardware_Process(void)
{
}

uint32_t Hardware_GetTickMs(void)
{
    return HAL_GetTick();
}

	
bool Hardware_ReadRoleSwitchIsMaster(void)
{
#if (APP_ROLE_DETECT_ENABLED != 0U)
    return (HAL_GPIO_ReadPin(APP_ROLE_DETECT_GPIO_PORT, APP_ROLE_DETECT_GPIO_PIN) ==
            APP_ROLE_DETECT_MASTER_LEVEL);
#else
    return (APP_ROLE_DEFAULT == APP_ROLE_MASTER);
#endif
}

void Hardware_SetRoleLed(bool on)
{
    const GPIO_PinState active = APP_ROLE_LED_ACTIVE_LEVEL;
    const GPIO_PinState inactive = (active == GPIO_PIN_SET) ? GPIO_PIN_RESET : GPIO_PIN_SET;

    HAL_GPIO_WritePin(APP_ROLE_LED_GPIO_PORT,
                      APP_ROLE_LED_GPIO_PIN,
                      on ? active : inactive);
}

bool Hardware_ReadButton(uint8_t index)
{
    uint16_t pin;

    switch (index)
    {
        case 0U:
            pin = APP_BUTTON1_GPIO_PIN;
            break;

        case 1U:
            pin = APP_BUTTON2_GPIO_PIN;
            break;

        case 2U:
            pin = APP_BUTTON3_GPIO_PIN;
            break;

        default:
            return false;
    }

    return (HAL_GPIO_ReadPin(APP_BUTTON_GPIO_PORT, pin) == APP_BUTTON_ACTIVE_LEVEL);
}

uint16_t Hardware_ReadAnalogRaw(void)
{
    return 0U;
}
