#include <string.h>

#include "esp_app_desc.h"
#include "esp_crt_bundle.h"
#include "esp_http_client.h"
#include "esp_https_ota.h"
#include "esp_log.h"
#include "esp_system.h"

#include "ota_update.h"

static const char *TAG = "ota_update";

/* Generous: the image is ~1.2MB and may stream over a WAN reverse
 * proxy; esp_https_ota resets this per-read, so it's an inactivity
 * timeout, not a total-transfer cap. */
#define OTA_HTTP_TIMEOUT_MS 30000

/* Built the same way as every other tools-server URL -- scheme/cert/
 * id/token handling all come from build_url()'s conventions. Duplicated
 * tiny helper rather than exporting frame_client.c's static build_url();
 * kept byte-identical in behavior (see frame_client.c). */
static void build_ota_url(char *out, size_t out_size, const frame_config_t *cfg)
{
    const char *toolsserver = cfg->toolsserver;
    size_t len;
    if (strncmp(toolsserver, "http://", 7) == 0 || strncmp(toolsserver, "https://", 8) == 0) {
        len = (size_t)snprintf(out, out_size, "%s/frame/firmware", toolsserver);
    } else {
        len = (size_t)snprintf(out, out_size, "http://%s/frame/firmware", toolsserver);
    }

    char device_id[FRAME_DEVICE_ID_LEN + 1];
    frame_device_id_get(device_id, sizeof(device_id));
    if (len < out_size) {
        len += (size_t)snprintf(out + len, out_size - len, "?id=%s", device_id);
    }

    const char *token = cfg->device_token[0] != '\0' ? cfg->device_token : cfg->access_token;
    if (token[0] != '\0' && len < out_size) {
        snprintf(out + len, out_size - len, "&token=%s", token);
    }
}

void ota_update_if_available(const frame_config_t *cfg, const char *server_version)
{
    if (server_version == NULL || server_version[0] == '\0') {
        return; /* server has no uploaded firmware */
    }

    const char *running = esp_app_get_description()->version;
    if (strcmp(server_version, running) == 0) {
        return; /* already running what the server has */
    }

    ESP_LOGI(TAG, "Firmware update available: running '%s', server has '%s' -- starting OTA", running,
             server_version);

    char url[256];
    build_ota_url(url, sizeof(url), cfg);

    esp_http_client_config_t http_config = {
        .url = url,
        .timeout_ms = OTA_HTTP_TIMEOUT_MS,
        .crt_bundle_attach = esp_crt_bundle_attach,
        .keep_alive_enable = true,
    };
    esp_https_ota_config_t ota_config = {
        .http_config = &http_config,
    };

    esp_err_t err = esp_https_ota(&ota_config);
    if (err != ESP_OK) {
        /* Not fatal -- the photo already displayed this cycle; we just
         * try again on a future wake. */
        ESP_LOGW(TAG, "OTA failed (%s), will retry on a later wake", esp_err_to_name(err));
        return;
    }

    ESP_LOGI(TAG, "OTA complete, restarting into '%s'", server_version);
    esp_restart();
}
