#pragma once

#include "esphome/core/defines.h"

#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <span>
#include <string>

#ifdef USE_TIME_TIMEZONE
#include "esphome/components/time/posix_tz.h"
#endif

namespace esphome {

template<typename T> bool increment_time_value(T &current, uint16_t begin, uint16_t end);

uint8_t days_in_month(uint8_t month, uint16_t year);

/// A more user-friendly version of struct tm from time.h
struct ESPTime {
  /// Buffer size required for strftime output
  static constexpr size_t STRFTIME_BUFFER_SIZE = 128;

  /** seconds after the minute [0-60]
   * @note second is generally 0-59; the extra range is to accommodate leap seconds.
   */
  uint8_t second;
  /// minutes after the hour [0-59]
  uint8_t minute;
  /// hours since midnight [0-23]
  uint8_t hour;
  /// day of the week; sunday=1 [1-7]
  uint8_t day_of_week;
  /// day of the month [1-31]
  uint8_t day_of_month;
  /// day of the year [1-366]
  uint16_t day_of_year;
  /// month; january=1 [1-12]
  uint8_t month;
  /// year
  uint16_t year;
  /// daylight saving time flag
  bool is_dst;
  /// unix epoch time (seconds since UTC Midnight January 1, 1970)
  time_t timestamp;

  /** Convert this ESPTime struct to a null-terminated c string buffer as specified by the format argument.
   * Up to buffer_len bytes are written.
   *
   * @see https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime
   */
  size_t strftime(char *buffer, size_t buffer_len, const char *format);

  /** Format time into a fixed-size buffer, returns length written.
   *
   * This is the preferred method for avoiding heap allocations. The buffer size is enforced at compile-time.
   * On format error, writes "ERROR" to the buffer and returns 5.
   * @see https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime
   */
  size_t strftime_to(std::span<char, STRFTIME_BUFFER_SIZE> buffer, const char *format);

  /** Convert this ESPTime struct to a string as specified by the format argument.
   * @see https://en.cppreference.com/w/c/chrono/strftime
   *
   * @warning This method returns a dynamically allocated string which can cause heap fragmentation with some
   * microcontrollers. Prefer strftime_to() for heap-free formatting.
   *
   * @warning This method can return "ERROR" when the underlying strftime() call fails or when the
   * output exceeds STRFTIME_BUFFER_SIZE bytes.
   */
  std::string strftime(const std::string &format);

  /// @copydoc strftime(const std::string &format)
  std::string strftime(const char *format);

  /// Check if this ESPTime is valid (year >= 2019 and the requested fields are in range).
  /// @param check_day_of_week validate day_of_week (not always available when constructing from date/time fields)
  /// @param check_day_of_year validate day_of_year (not always available when constructing from date/time fields)
  bool is_valid(bool check_day_of_week = true, bool check_day_of_year = true) const {
    return this->year >= 2019 && this->fields_in_range(check_day_of_week, check_day_of_year);
  }

  /// Check if time fields are in range.
  /// @param check_day_of_week validate day_of_week (not always available when constructing from date/time fields)
  /// @param check_day_of_year validate day_of_year (not always available when constructing from date/time fields)
  bool fields_in_range(bool check_day_of_week = true, bool check_day_of_year = true) const {
    bool valid = this->second < 61 && this->minute < 60 && this->hour < 24 && this->month > 0 && this->month < 13 &&
                 this->day_of_month > 0 && this->day_of_month <= days_in_month(this->month, this->year);
    if (check_day_of_week) {
      valid = valid && this->day_of_week > 0 && this->day_of_week < 8;
    }
    if (check_day_of_year) {
      valid = valid && this->day_of_year > 0 && this->day_of_year < 367;
    }
    return valid;
  }

  /** Convert a string to ESPTime struct as specified by the format argument.
   * @param time_to_parse c string formatted like this: 2020-08-25 05:30:00.
   * @param len length of the string (not including null terminator if present)
   * @param esp_time an instance of a ESPTime struct
   * @return the success state of the parsing
   */
  static bool strptime(const char *time_to_parse, size_t len, ESPTime &esp_time);
  /// @copydoc strptime(const char *, size_t, ESPTime &)
  static bool strptime(const char *time_to_parse, ESPTime &esp_time) {
    return strptime(time_to_parse, strlen(time_to_parse), esp_time);
  }
  /// @copydoc strptime(const char *, size_t, ESPTime &)
  static bool strptime(const std::string &time_to_parse, ESPTime &esp_time) {
    return strptime(time_to_parse.c_str(), time_to_parse.size(), esp_time);
  }

  /// Convert a C tm struct instance with a C unix epoch timestamp to an ESPTime instance.
  static ESPTime from_c_tm(struct tm *c_tm, time_t c_time);

  /** Convert an UTC epoch timestamp to a local time ESPTime instance.
   *
   * @param epoch Seconds since 1st January 1970. In UTC.
   * @return The generated ESPTime
   */
  static ESPTime from_epoch_local(time_t epoch) {
#ifdef USE_TIME_TIMEZONE
    struct tm local_tm;
    if (time::epoch_to_local_tm(epoch, time::get_global_tz(), &local_tm)) {
      return ESPTime::from_c_tm(&local_tm, epoch);
    }
    // Fallback to UTC if conversion failed
    return ESPTime::from_epoch_utc(epoch);
#else
    // No timezone support - return UTC (no TZ configured, localtime would return UTC anyway)
    return ESPTime::from_epoch_utc(epoch);
#endif
  }
  /** Convert an UTC epoch timestamp to a UTC time ESPTime instance.
   *
   * @param epoch Seconds since 1st January 1970. In UTC.
   * @return The generated ESPTime
   */
  static ESPTime from_epoch_utc(time_t epoch) {
    struct tm *c_tm = ::gmtime(&epoch);
    if (c_tm == nullptr) {
      return ESPTime{};  // Return an invalid ESPTime
    }
    return ESPTime::from_c_tm(c_tm, epoch);
  }

  /// Recalculate the timestamp field from the other fields of this ESPTime instance (must be UTC).
  void recalc_timestamp_utc(bool use_day_of_year = true);

  /// Recalculate the timestamp field from the other fields of this ESPTime instance assuming local fields.
  void recalc_timestamp_local();

  /// Convert this ESPTime instance back to a tm struct.
  struct tm to_c_tm();

  static int32_t timezone_offset();

  /// Increment this clock instance by one second.
  void increment_second();
  /// Increment this clock instance by one day.
  void increment_day();
  bool operator<(const ESPTime &other) const;
  bool operator<=(const ESPTime &other) const;
  bool operator==(const ESPTime &other) const;
  bool operator>=(const ESPTime &other) const;
  bool operator>(const ESPTime &other) const;
};
}  // namespace esphome
