import logging
from typing import Any

import esphome.config_validation as cv
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER, CONF_SCL, CONF_SDA
from esphome.pins import check_strapping_pin

# https://github.com/espressif/esp-idf/blob/master/components/esp_hal_i2c/esp32c6/include/hal/i2c_ll.h
_ESP32C6_I2C_LP_PINS = {"SDA": 6, "SCL": 7}

_ESP32C6_SPI_PSRAM_PINS = {
    24: "SPICS0",
    25: "SPIQ",
    26: "SPIWP",
    27: "VDD_SPI",
    28: "SPIHD",
    29: "SPICLK",
    30: "SPID",
}

_ESP32C6_USB_JTAG_PINS = {12, 13}

_ESP32C6_STRAPPING_PINS = {4, 5, 8, 9, 15}

_LOGGER = logging.getLogger(__name__)


def esp32_c6_validate_gpio_pin(value: int) -> int:
    if value < 0 or value > 30:
        raise cv.Invalid(f"Invalid pin number: {value} (must be 0-30)")
    if value in _ESP32C6_SPI_PSRAM_PINS:
        raise cv.Invalid(
            f"This pin cannot be used on ESP32-C6s and is already used by the SPI/PSRAM interface (function: {_ESP32C6_SPI_PSRAM_PINS[value]})"
        )
    if value in _ESP32C6_USB_JTAG_PINS:
        _LOGGER.warning(
            "GPIO%d is used by the USB-Serial-JTAG interface."
            " Using this pin as GPIO will conflict with USB-Serial-JTAG.",
            value,
        )

    return value


def esp32_c6_validate_supports(value: dict[str, Any]) -> dict[str, Any]:
    num = value[CONF_NUMBER]
    mode = value[CONF_MODE]
    is_input = mode[CONF_INPUT]

    if num < 0 or num > 30:
        raise cv.Invalid(f"Invalid pin number: {num} (must be 0-30)")
    if is_input:
        # All ESP32 pins support input mode
        pass

    check_strapping_pin(value, _ESP32C6_STRAPPING_PINS, _LOGGER)
    return value


def esp32_c6_validate_lp_i2c(value):
    lp_sda_pin = _ESP32C6_I2C_LP_PINS["SDA"]
    lp_scl_pin = _ESP32C6_I2C_LP_PINS["SCL"]
    if int(value[CONF_SDA]) != lp_sda_pin or int(value[CONF_SCL]) != lp_scl_pin:
        raise cv.Invalid(
            f"Low power i2c interface is only supported on GPIO{lp_sda_pin} SDA and GPIO{lp_scl_pin} SCL for ESP32-C6"
        )
    return value
