/*
 * IR Send Library - PWM-based carrier generation
 */

#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/drivers/pwm.h>

#include "ir_send.h"

LOG_MODULE_REGISTER(ir_send_lib);

static const struct pwm_dt_spec ir_pwm = PWM_DT_SPEC_GET(DT_ALIAS(ir_output));
static uint32_t carrier_freq = 38000; /* Standard IR carrier frequency in Hz */

int ir_send_init(void)
{
	if (!device_is_ready(ir_pwm.dev)) {
		LOG_ERR("IR PWM device not ready!");
		return -ENODEV;
	}

	LOG_INF("IR output PWM ready: dev=%p, channel=%u", ir_pwm.dev, ir_pwm.channel);
	return 0;
}

int ir_send_pulse(uint32_t duration_us)
{
	return ir_send_burst_us(duration_us);
}

int ir_send_message(const uint8_t *data, uint8_t len)
{
	if (!device_is_ready(ir_pwm.dev)) {
		return -ENODEV;
	}

	LOG_DBG("Sending IR message (%u bytes)", len);
	
	/* TODO: Implement IR protocol encoding (e.g., NEC, custom protocol)
	 * For now, just a placeholder that sends a test pulse.
	 */
	ir_send_pulse(1000); /* 1ms test pulse */

	return 0;
}

void ir_send_set_frequency(uint32_t freq_hz)
{
	carrier_freq = freq_hz;
	LOG_DBG("IR carrier frequency set to %u Hz", carrier_freq);
}

int ir_send_burst_us(uint32_t burst_us)
{
	if (!device_is_ready(ir_pwm.dev)) {
		return -ENODEV;
	}

	uint64_t period_ns = PWM_HZ(carrier_freq);
	uint64_t duty_ns = period_ns / 2U; /* 50% duty cycle */

	int ret = pwm_set_dt(&ir_pwm, period_ns, duty_ns);
	if (ret != 0) {
		LOG_ERR("Failed to enable PWM burst: %d", ret);
		return ret;
	}

	k_usleep(burst_us);

	/* Stop carrier after burst */
	ret = pwm_set_dt(&ir_pwm, period_ns, 0);
	if (ret != 0) {
		LOG_ERR("Failed to stop PWM after burst: %d", ret);
	}

	return ret;
}
