/*
 * Copyright (C) 2026 Sophie Sitzler
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

// @file tpee.h
// @desc A low-key HTTP micro-framework for people who hate web bloat

#pragma once

#include <stdbool.h>
#include <sys/socket.h>

#ifdef TPEE_IMPL
#define SOCK_IMPL
#endif // TPEE_IMPL

// @include <sock.h>
// @desc sock library handling server/client communication and multi-threading.
#include <sock.h>

// @enum tpee_err_t
// @desc Error code.
typedef enum {
  TPEE_ERR_OK = SOCK_ERR_OK,
  TPEE_ERR__COUNT,
} tpee_err_t;

// @enum tpee_method_t
// @desc tpee method type.
typedef enum {
  TPEE_METHOD_GET,
  TPEE_METHOD_HEAD,
  TPEE_METHOD_POST,
  TPEE_METHOD_PUT,
  TPEE_METHOD_DELETE,
  TPEE_METHOD_CONNECT,
  TPEE_METHOD_OPTIONS,
  TPEE_METHOD_TRACE,
  TPEE_METHOD_PATCH,
} tpee_method_t;

// @enum tpee_status_t
// @desc tpee status code.
typedef enum {
  TPEE_STATUS_CONTINUE                        = 100,
  TPEE_STATUS_SWITCHING_PROTOCOLS             = 101,
  TPEE_STATUS_PROCESSING                      = 102,
  TPEE_STATUS_EARLY_HINTS                     = 103,
  TPEE_STATUS_OK                              = 200,
  TPEE_STATUS_CREATED                         = 201,
  TPEE_STATUS_ACCEPTED                        = 202,
  TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION   = 203,
  TPEE_STATUS_NO_CONTENT                      = 204,
  TPEE_STATUS_RESET_CONTENT                   = 205,
  TPEE_STATUS_PARTIAL_CONTENT                 = 206,
  TPEE_STATUS_MULTI_STATUS                    = 207,
  TPEE_STATUS_ALREADY_REPORTED                = 208,
  TPEE_STATUS_IM_USED                         = 226,
  TPEE_STATUS_MULTIPLE_CHOICES                = 300,
  TPEE_STATUS_MOVED_PERMANENTLY               = 301,
  TPEE_STATUS_FOUND                           = 302,
  TPEE_STATUS_SEE_OTHER                       = 303,
  TPEE_STATUS_NOT_MODIFIED                    = 304,
  TPEE_STATUS_TEMPORARY_REDIRECT              = 307,
  TPEE_STATUS_PERMANENT_REDIRECT              = 308,
  TPEE_STATUS_BAD_REQUEST                     = 400,
  TPEE_STATUS_UNAUTHORIZED                    = 401,
  TPEE_STATUS_PAYMENT_REQUIRED                = 402,
  TPEE_STATUS_FORBIDDEN                       = 403,
  TPEE_STATUS_NOT_FOUND                       = 404,
  TPEE_STATUS_METHOD_NOT_ALLOWED              = 405,
  TPEE_STATUS_NOT_ACCEPTABLE                  = 406,
  TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED   = 407,
  TPEE_STATUS_REQUEST_TIMEOUT                 = 408,
  TPEE_STATUS_CONFLICT                        = 409,
  TPEE_STATUS_GONE                            = 410,
  TPEE_STATUS_LENGTH_REQUIRED                 = 411,
  TPEE_STATUS_PRECONDITION_FAILED             = 412,
  TPEE_STATUS_PAYLOAD_TOO_LARGE               = 413,
  TPEE_STATUS_URI_TOO_LONG                    = 414,
  TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE          = 415,
  TPEE_STATUS_RANGE_NOT_SATISFIABLE           = 416,
  TPEE_STATUS_EXPECTATION_FAILED              = 417,
  TPEE_STATUS_I_AM_A_TEAPOT                   = 418,
  TPEE_STATUS_MISDIRECTED_REQUEST             = 421,
  TPEE_STATUS_UNPROCESSABLE_CONTENT           = 422,
  TPEE_STATUS_LOCKED                          = 423,
  TPEE_STATUS_FAILED_DEPENDENCY               = 424,
  TPEE_STATUS_TOO_EARLY                       = 425,
  TPEE_STATUS_UPGRADE_REQUIRED                = 426,
  TPEE_STATUS_PRECONDITION_REQUIRED           = 428,
  TPEE_STATUS_TOO_MANY_REQUESTS               = 429,
  TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
  TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS   = 451,
  TPEE_STATUS_INTERNAL_SERVER_ERROR           = 500,
  TPEE_STATUS_NOT_IMPLEMENTED                 = 501,
  TPEE_STATUS_BAD_GATEWAY                     = 502,
  TPEE_STATUS_SERVICE_UNAVAILABLE             = 503,
  TPEE_STATUS_GATEWAY_TIMEOUT                 = 504,
  TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED      = 505,
  TPEE_STATUS_VARIANT_ALSO_NEGOTITATES        = 506,
  TPEE_STATUS_INSUFFICIENT_STORAGE            = 507,
  TPEE_STATUS_LOOP_DETECTED                   = 508,
  TPEE_STATUS_NOT_EXTENDED                    = 510,
  TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,
  __TPEE_STATUS_HANDLED                       = 999,
} tpee_status_t;

// @struct tpee_t
// @groupdef tpee_t
// @desc Global context struct. Implemented here {tpee}.
typedef struct tpee tpee_t;

// @type tpee_host_t
// @desc Represents the host.
typedef sock_host_t tpee_host_t;

// @type tpee_bind_t
// @desc Represents the binding (port).
typedef sock_bind_t tpee_bind_t;

// @type tpee_conn_t
// @groupdef tpee_conn_t
// @desc Represents a client connection.
typedef sock_conn_t tpee_conn_t;

// @struct tpee_header_t
// @desc A tpee header.
typedef struct {
  char *key;
  char *value;
} tpee_header_t;

// @struct tpee_req_t
// @groupdef tpee_req_t
// @desc A tpee request struct.
typedef struct {
  tpee_conn_t *conn;
  char *method;
  char *url;
  char *version;
  tpee_header_t *headers;
  int headers_len;
  char *body;
  long body_len;
  void *ext_data;
} tpee_req_t;

// @struct tpee_resp_t
// @groupdef tpee_resp_t
// @desc A tpee response struct.
typedef struct {
  char *version;
  tpee_status_t status;
  tpee_header_t *headers;
  int headers_len;
  char *body;
  long body_len;
} tpee_resp_t;

// @type tpee_global_fn_t
// @desc A function type for a global route handler.
typedef tpee_resp_t (*tpee_global_fn_t)(tpee_t *, tpee_req_t *);

// @type tpee_handle_fn_t
// @desc A function type for a route handler.
typedef tpee_resp_t (*tpee_handle_fn_t)(tpee_req_t *);

// @type tpee_hook_fn_t
// @desc A function type for a hook handler.
typedef void (*tpee_hook_fn_t)(tpee_req_t *);

// @struct tpee_route_t
// @desc A route.
typedef struct {
  tpee_method_t method;
  char *path;
  tpee_handle_fn_t fn;
} tpee_route_t;

// @struct tpee_pair_t
typedef struct {
  char *key;
  char *value;
} tpee_pair_t;

// @struct tpee_pair_list_t
// @groupdef tpee_pair_list_t
typedef struct {
  tpee_pair_t *pair_list;
  size_t len;
} tpee_pair_list_t;

// @impl tpee_t
struct tpee {
  sock_t *sock;
  tpee_global_fn_t fn;
};

// @func tpee_init
// @group tpee_t
// @desc Initializes global library context {tpee_t}. Free with {tpee_cleanup}.
// @return {tpee_t} * - Returns the global library context.
tpee_t *tpee_init(void);

// @func tpee_cleanup
// @group tpee_t
// @desc Cleans up {tpee_t}.
// @param {tpee_t} *self - The global library context.
void tpee_cleanup(tpee_t *self);

// @func tpee_on_global
// @group tpee_t
// @desc Set and override the default global route handler {_tpee_on_global}.
// @param {tpee_t} *self - The global library context.
// @param {tpee_global_fn_t} fn - The global route handler.
void tpee_on_global(tpee_t *self, tpee_global_fn_t fn);

// @func tpee_on_route
// @note Use macros like {TPEE_GET} and others to register routes more easily.
// @desc Registers a new route.
// @param {tpee_method_t} method - The tpee method.
// @param char *url - The tpee URL (path).
// @param {tpee_handle_fn_t} fn - The route handler.
void tpee_on_route(tpee_method_t method, char *url, tpee_handle_fn_t fn);

// @func tpee_on_default
// @note Use macro {TPEE_DEFAULT} instead.
// @desc Registers a fallback handler.
// @param {tpee_handle_fn_t} fn - The route handler.
void tpee_on_default(tpee_handle_fn_t fn);

// @func tpee_on_pre_route
// @note Use macro {TPEE_PRE_HOOK} instead.
// @desc Registers a hook handler which is performed before the route handler is executed.
// @param {tpee_hook_fn_t} fn - The hook handler.
void tpee_on_pre_route(tpee_hook_fn_t fn);

// @func tpee_on_post_route
// @note Use macro {TPEE_POST_HOOK} instead.
// @desc Registers a hook handler which is performed after the route handler is executed.
// @param {tpee_hook_fn_t} fn - The hook handler.
void tpee_on_post_route(tpee_hook_fn_t fn);

// @func tpee_req_path
// @group tpee_req_t
// @param {tpee_req_t} *req - The tpee request.
// @return char * - Returns the request path.
char *tpee_req_path(tpee_req_t *req);

// @func tpee_req_body
// @group tpee_req_t
// @param {tpee_req_t} *req - The tpee request.
// @return char * - Returns the request body.
char *tpee_req_body(tpee_req_t *req);

// @func tpee_req_queries
// @group tpee_req_t
// @param {tpee_req_t} *req - The tpee request.
// @return {tpee_pair_list_t} - Returns the request queries.
tpee_pair_list_t tpee_req_queries(tpee_req_t *req);

// @func tpee_req_params
// @group tpee_req_t
// @param {tpee_req_t} *req - The tpee request.
// @return {tpee_pair_list_t} - Returns the request params.
tpee_pair_list_t tpee_req_params(tpee_req_t *req);

// @func tpee_pair_list_get
// @group tpee_pair_list_t
char *tpee_pair_list_get(tpee_pair_list_t *self, char *key);

// @func tpee_pair_list_has
// @group tpee_pair_list_t
bool tpee_pair_list_has(tpee_pair_list_t *self, char *key);

// @func tpee_pair_list_free
// @group tpee_pair_list_t
void tpee_pair_list_free(tpee_pair_list_t *self);

// @func tpee_conn_read
// @group tpee_conn_t
// @param {tpee_conn_t} *conn - The connection.
// @param char * - The buffer to read into.
// @param size_t - The size of the buffer.
ssize_t tpee_conn_read(tpee_conn_t *conn, char *buffer, size_t len);

// @func tpee_conn_write
// @group tpee_conn_t
// @param {tpee_conn_t} *conn - The connection.
// @param char * - The buffer to be written.
// @param size_t - The size of the buffer.
ssize_t tpee_conn_write(tpee_conn_t *conn, char *buffer, size_t len);

// @func tpee_req_header
// @group tpee_req_t
// @param {tpee_req_t} *req - The tpee request.
// @param char *key - The header key.
// @return char * - Returns a header value.
char *tpee_req_header(tpee_req_t *req, char *key);

// @func tpee_resp_header
// @group tpee_resp_t
// @desc Writes a header to the response. The header content is consumed and can be freed afterward.
// @param {tpee_resp_t} *resp - The tpee response.
// @param char *key - The header key.
// @param char *value - The header value.
void tpee_resp_header(tpee_resp_t *resp, char *key, char *value);

// @func tpee_resp_create
// @group tpee_resp_t
// @desc Creates a new response with a given tpee status. Freed with {tpee_resp_free}.
// @param {tpee_status_t} status - The tpee status code.
// @return {tpee_resp_t} - Returns a tpee response.
tpee_resp_t tpee_resp_create(tpee_status_t status);

// @func tpee_resp_body
// @group tpee_resp_t
// @desc Writes body content to the response. The body content is consumed and can be freed afterward.
// @param {tpee_resp_t} *resp - The tpee response.
// @param char *body - The body content.
// @param long len - The body  length.
void tpee_resp_body(tpee_resp_t *resp, char *body, long len);

// @func tpee_req_free
// @group tpee_req_t
// @desc Frees a request.
// @param {tpee_req_t} *req - The tpee request.
void tpee_req_free(tpee_req_t *req);

// @func tpee_resp_write_head
// @group tpee_resp_t
// @desc Writes a response header  to the socket stream.
// @param {tpee_resp_t} *resp - The tpee response.
// @param {tpee_conn_t} *conn - The tpee connection.
void tpee_resp_write_head(tpee_resp_t *resp, tpee_conn_t *conn);

// @func tpee_resp_write_body
// @group tpee_resp_t
// @desc Writes a response body to the socket stream.
// @param {tpee_resp_t} *resp - The tpee response.
// @param {tpee_conn_t} *conn - The tpee connection.
void tpee_resp_write_body(tpee_resp_t *resp, tpee_conn_t *conn);

// @func tpee_resp_write
// @group tpee_resp_t
// @desc Writes a response to the socket stream.
// @param {tpee_resp_t} *resp - The tpee response.
// @param {tpee_conn_t} *conn - The tpee connection.
void tpee_resp_write(tpee_resp_t *resp, tpee_conn_t *conn);

// @func tpee_resp_free
// @group tpee_resp_t
// @desc Frees a response.
// @param {tpee_resp_t} *resp - The tpee response.
void tpee_resp_free(tpee_resp_t *resp);

// @func tpee_bind
// @group tpee_t
// @param {tpee_t} *self - The global library context.
// @param char *hostname - The hostname.
// @param int port - The port.
// @param {tpee_host_t} *hosts - The host to bind to.
// @param int hosts_len - The host length of to be bound host.
tpee_err_t tpee_bind(tpee_t *self, char *hostname, int port, tpee_host_t *hosts, int hosts_len);

// @func tpee_listen
// @group tpee_t
// @param {tpee_t} *self - The global library context.
tpee_err_t tpee_listen(tpee_t *self);

// @func tpee_bind_listen
// @group tpee_t
// @param {tpee_t} *self - The global library context.
// @param char *hostname - The hostname.
// @param int port - The port.
tpee_err_t tpee_bind_listen(tpee_t *self, char *hostname, int port);

// @func tpee_close
// @group tpee_t
// @param {tpee_t} *self - The global library context.
void tpee_close(tpee_t *self);

// @func _tpee_req_read
// @group tpee_req_t
// @internal
// @param {tpee_req_t} *req - The tpee request.
// @param {tpee_conn_t} *conn - The tpee connection.
// @return {tpee_err_t} - Returns an tpee error code.
tpee_err_t _tpee_req_read(tpee_req_t *req, tpee_conn_t *conn);

// @func _tpee_method_str
// @internal
// @desc Get tpee method string.
const char *_tpee_method_str(tpee_method_t method);

// @macro TPEE_RESP_HANDLED
// @group tpee_resp_t
// @desc Handled {tpee_resp_t}.
#define TPEE_RESP_HANDLED (tpee_resp_t) { .status = __TPEE_STATUS_HANDLED }

// @macro _TPEE_ON
// @internal
#define _TPEE_ON(method, path, fn_name) \
  static tpee_resp_t fn_name(tpee_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_tpee_fn_register_##fn_name(void) { \
    tpee_on_route(method, path, &fn_name); \
  } \
  static tpee_resp_t fn_name(tpee_req_t *req)

// @macro TPEE_GET
#define TPEE_GET(path, fn_name) _TPEE_ON(TPEE_METHOD_GET, path, fn_name)

// @macro TPEE_HEAD
#define TPEE_HEAD(path, fn_name) _TPEE_ON(TPEE_METHOD_HEAD, path, fn_name)

// @macro TPEE_POST
#define TPEE_POST(path, fn_name) _TPEE_ON(TPEE_METHOD_POST, path, fn_name)

// @macro TPEE_PUT
#define TPEE_PUT(path, fn_name) _TPEE_ON(TPEE_METHOD_PUT, path, fn_name)

// @macro TPEE_DELETE
#define TPEE_DELETE(path, fn_name) _TPEE_ON(TPEE_METHOD_DELETE, path, fn_name)

// @macro TPEE_CONNECT
#define TPEE_CONNECT(path, fn_name) _TPEE_ON(TPEE_METHOD_CONNECT, path, fn_name)

// @macro TPEE_OPTIONS
#define TPEE_OPTIONS(path, fn_name) _TPEE_ON(TPEE_METHOD_OPTIONS, path, fn_name)

// @macro TPEE_TRACE
#define TPEE_TRACE(path, fn_name) _TPEE_ON(TPEE_METHOD_TRACE, path, fn_name)

// @macro TPEE_PATCH
#define TPEE_PATCH(path, fn_name) _TPEE_ON(TPEE_METHOD_PATCH, path, fn_name)

// @macro TPEE_DEFAULT
#define TPEE_DEFAULT(fn_name) \
  static tpee_resp_t fn_name(tpee_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_tpee_fn_register_##fn_name(void) { \
    tpee_on_default(&fn_name); \
  } \
  static tpee_resp_t fn_name(tpee_req_t *req)

// @macro TPEE_PRE_HOOK
#define TPEE_PRE_HOOK(fn_name) \
  static void fn_name(tpee_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_tpee_fn_register_##fn_name(void) { \
    tpee_on_pre_route(&fn_name); \
  } \
  static void fn_name(tpee_req_t *req)

// @macro TPEE_POST_HOOK
#define TPEE_POST_HOOK(fn_name) \
  static void fn_name(tpee_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_tpee_fn_register_##fn_name(void) { \
    tpee_on_post_route(&fn_name); \
  } \
  static void fn_name(tpee_req_t *req)

#ifdef TPEE_IMPL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <netdb.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>

// @macro TPEE_VERSION
// @internal
#define TPEE_VERSION "HTTP/1.1"

// @macro TPEE_MAX_REQUEST_HEAD_SIZE
// @internal
#define TPEE_MAX_REQUEST_HEAD_SIZE 1000000

// @var _tpee_route_list
// @internal
tpee_route_t *_tpee_route_list = NULL;

// @var _tpee_route_list_len
// @internal
size_t _tpee_route_list_len = 0;

// @var _tpee_default_route
// @internal
tpee_handle_fn_t _tpee_default_route;

// @var _tpee_pre_route
// @internal
tpee_hook_fn_t _tpee_pre_route;

// @var _tpee_post_route
// @internal
tpee_hook_fn_t _tpee_post_route;

// @func _tpee_on_global
// @group tpee_t
// @internal
// @desc The default route handler. Can be overwritten with {tpee_on_global}.
// @param {tpee_t} *self - The global library context.
// @param {tpee_req_t} *req - The tpee request.
// @return {tpee_resp_t} - Returns a tpee response.
tpee_resp_t _tpee_on_global(tpee_t *self, tpee_req_t *req) {
  (void) self;
  tpee_resp_t resp = tpee_resp_create(TPEE_STATUS_NOT_FOUND);
  if (_tpee_pre_route != NULL) {
    _tpee_pre_route(req);
  }
  for (size_t i = 0; i < _tpee_route_list_len; i++) {
    tpee_route_t *route = &_tpee_route_list[i];
    const char *method = _tpee_method_str(route->method);
    char *path = tpee_req_path(req);
    if (strcmp(method, req->method) == 0) {
      size_t len = strlen(route->path);
      char c = route->path[len - 1];
      if (c == '*') {
        if (strncmp(route->path, path, len - 1) == 0) {
          tpee_resp_free(&resp);
          resp = route->fn(req);
        }
      }
      else {
        if (strcmp(route->path, path) == 0) {
          tpee_resp_free(&resp);
          resp = route->fn(req);
        }
      }
    }
    free(path);
    if (resp.status != TPEE_STATUS_NOT_FOUND) {
      if (_tpee_post_route != NULL) {
        _tpee_post_route(req);
      }
      return resp;
    }
  }
  if (_tpee_default_route != NULL) {
    tpee_resp_free(&resp);
    resp = _tpee_default_route(req);
  }
  if (_tpee_post_route != NULL) {
    _tpee_post_route(req);
  }
  return resp;
}

// @func _tpee_on_handle
// @internal
sock_err_t _tpee_on_handle(sock_t *sock, tpee_conn_t *conn) {
  tpee_t *self= (tpee_t *) sock->ext;
  tpee_req_t req;
  tpee_err_t err = _tpee_req_read(&req, conn);
  if (err != TPEE_ERR_OK) {
    return (sock_err_t) err;
  }
  if (req.method != NULL && req.url != NULL) {
    if (self->fn != NULL) {
      tpee_resp_t resp = self->fn(self, &req);
      tpee_resp_write(&resp, conn);
      tpee_resp_free(&resp);
    }
  }
  tpee_req_free(&req);
  return (sock_err_t) TPEE_ERR_OK;
}

// @impl tpee_init
tpee_t *tpee_init(void) {
  tpee_t *self = (tpee_t *) malloc(sizeof(tpee_t));
  *self = (tpee_t) {
    .sock = sock_init(),
    .fn = &_tpee_on_global,
  };
  sock_set_ext(self->sock, self);
  sock_on_global(self->sock, _tpee_on_handle);
  return self;
}

// @impl tpee_cleanup
void tpee_cleanup(tpee_t *self) {
  if (self->sock != NULL) {
    sock_cleanup(self->sock);
  }
  if (_tpee_route_list != NULL && _tpee_route_list_len > 0) {
    for (size_t i = 0; i < _tpee_route_list_len; i++) {
      tpee_route_t *route = &_tpee_route_list[i];
      if (route->path) free(route->path);
    }
    free(_tpee_route_list);
    _tpee_route_list = NULL;
    _tpee_route_list_len = 0;
  }
  free(self);
}

// @impl tpee_on_global
void tpee_on_global(tpee_t *self, tpee_global_fn_t fn) {
  self->fn = fn;
}

// @impl tpee_on_route
void tpee_on_route(tpee_method_t method, char *path, tpee_handle_fn_t fn) {
  _tpee_route_list = realloc(_tpee_route_list, sizeof(tpee_route_t) * (_tpee_route_list_len + 1));
  _tpee_route_list[_tpee_route_list_len] = (tpee_route_t) {
    .method = method,
    .path = strdup(path),
    .fn = fn,
  };
  _tpee_route_list_len++;
}

// @impl tpee_on_default
void tpee_on_default(tpee_handle_fn_t fn) {
  _tpee_default_route = fn;
}

// @impl tpee_on_pre_route
void tpee_on_pre_route(tpee_hook_fn_t fn) {
  _tpee_pre_route = fn;
}

// @impl tpee_on_post_route
void tpee_on_post_route(tpee_hook_fn_t fn) {
  _tpee_post_route = fn;
}

// @impl tpee_req_path
char *tpee_req_path(tpee_req_t *req) {
  char *uri = req->url;
  size_t url_len = strlen(uri);
  size_t i = 0;
  for (; i < url_len; i++) {
    size_t c = uri[i];
    if (c == '?') {
      break;
    }
  }
  size_t len = i;
  char *path = malloc(len + 1);
  memcpy(path, uri, len);
  path[len] = '\0';
  return path;
}

// @impl tpee_req_body
char *tpee_req_body(tpee_req_t *req) {
  return req->body;
}

// @func _tpee_pair_decode
// @internal
char *_tpee_pair_decode(char *str, size_t len) {
  size_t j = 0;
  size_t k = 0;
  char decoded[len + 1];
  while (j < len) {
    if (str[j] == '%') {
      if (j + 2 < len && isxdigit(str[j + 1]) && isxdigit(str[j + 2])) {
        char hex[3] = { str[j + 1], str[j + 2], '\0' };
        decoded[k++] = (char) strtol(hex, NULL, 16);
        j += 3;
        continue;
      }
      decoded[k++] = '%';
      j++;
      continue;
    }
    if (str[j] == '+') {
      decoded[k++] = ' ';
      j++;
      continue;
    }
    decoded[k++] = str[j++];
  }
  decoded[k] = '\0';
  size_t ret_len = strlen(decoded);
  char *ret = malloc(ret_len + 1);
  memcpy(ret, decoded, ret_len);
  ret[ret_len] = '\0';
  return ret;
}

// @func _tpee_pair_list_init
// @group tpee_pair_list_t
// @internal
tpee_pair_list_t _tpee_pair_list_init(char *uri) {
  tpee_pair_list_t self = (tpee_pair_list_t) {
    .pair_list = NULL,
    .len = 0,
  };
  size_t url_len = strlen(uri);
  size_t set = 0;
  size_t lim = 0;
  for (size_t i = 0; i < url_len + 1; i++) {
    // find 'key=value' pair
    if (i == url_len || uri[i] == '&') {
      size_t key_len = i - set;
      if (key_len > 0) {
        if (lim > set) {
          key_len = lim - set;
        }
        self.pair_list = realloc(self.pair_list, sizeof(tpee_pair_t) * (self.len + 1));
        tpee_pair_t *pair = &self.pair_list[self.len];
        // read key
        pair->key = _tpee_pair_decode(uri + set, key_len);
        pair->value = NULL;
        if (i > set + key_len + 1) {
          // read value
          size_t value_len = i - (set + key_len + 1);
          pair->value = _tpee_pair_decode(uri + set + key_len + 1, value_len);
        }
        self.len++;
      }
      set = i + 1;
    }
    // find '=' delimiter
    if (uri[i] == '=') {
      lim = i;
    }
  }
  return self;
}

// @impl tpee_req_queries
tpee_pair_list_t tpee_req_queries(tpee_req_t *req) {
  size_t url_len = strlen(req->url);
  // skip path
  for (size_t i = 0; i < url_len; i++) {
    if (req->url[i] == '?') {
      return _tpee_pair_list_init(req->url + i + 1);
    }
  }
  return (tpee_pair_list_t) {
    .pair_list = NULL,
    .len = 0,
  };
}

// @impl tpee_req_params
tpee_pair_list_t tpee_req_params(tpee_req_t *req) {
  return _tpee_pair_list_init(req->body);
}

// @impl tpee_pair_list_get
char *tpee_pair_list_get(tpee_pair_list_t *self, char *key) {
  if (self && self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      tpee_pair_t *pair = &self->pair_list[i];
      if (strcmp(pair->key, key) == 0) {
        return pair->value;
      }
    }
  }
  return NULL;
}

// @impl tpee_pair_list_has
bool tpee_pair_list_has(tpee_pair_list_t *self, char *key) {
  if (self && self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      tpee_pair_t *pair = &self->pair_list[i];
      if (strcmp(pair->key, key) == 0) {
        return true;
      }
    }
  }
  return false;
}

// @impl tpee_pair_list_free
void tpee_pair_list_free(tpee_pair_list_t *self) {
  if (self == NULL) {
    return;
  }
  if (self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      tpee_pair_t *pair = &self->pair_list[i];
      free(pair->key);
      if (pair->value) {
        free(pair->value);
      }
    }
    free(self->pair_list);
  }
}

// @impl _tpee_method_str
const char *_tpee_method_str(tpee_method_t method) {
  switch (method) {
    case TPEE_METHOD_GET:
      return "GET";
    case TPEE_METHOD_HEAD:
      return "HEAD";
    case TPEE_METHOD_POST:
      return "POST";
    case TPEE_METHOD_PUT:
      return "PUT";
    case TPEE_METHOD_DELETE:
      return "DELETE";
    case TPEE_METHOD_CONNECT:
      return "CONNECT";
    case TPEE_METHOD_OPTIONS:
      return "OPTIONS";
    case TPEE_METHOD_TRACE:
      return "TRACE";
    case TPEE_METHOD_PATCH:
      return "PATCH";
    default:
      return NULL;
  }
}

// @func _tpee_status_str
// @internal
const char *_tpee_status_str(tpee_status_t status) {
  switch (status) {
    case TPEE_STATUS_CONTINUE:
      return "Continue";
    case TPEE_STATUS_SWITCHING_PROTOCOLS:
      return "Switching Protocols";
    case TPEE_STATUS_PROCESSING:
      return "Processing";
    case TPEE_STATUS_EARLY_HINTS:
      return "Early Hints";
    case TPEE_STATUS_OK:
      return "OK";
    case TPEE_STATUS_CREATED:
      return "Created";
    case TPEE_STATUS_ACCEPTED:
      return "Accepted";
    case TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION:
      return "Non-Authoritative Information";
    case TPEE_STATUS_NO_CONTENT:
      return "No Content";
    case TPEE_STATUS_RESET_CONTENT:
      return "Reset Content";
    case TPEE_STATUS_PARTIAL_CONTENT:
      return "Partial Content";
    case TPEE_STATUS_MULTI_STATUS:
      return "Multi-Status";
    case TPEE_STATUS_ALREADY_REPORTED:
      return "Already Reported";
    case TPEE_STATUS_IM_USED:
      return "IM Used";
    case TPEE_STATUS_MULTIPLE_CHOICES:
      return "Multiple Choices";
    case TPEE_STATUS_MOVED_PERMANENTLY:
      return "Moved Permanently";
    case TPEE_STATUS_FOUND:
      return "Found";
    case TPEE_STATUS_SEE_OTHER:
      return "See Other";
    case TPEE_STATUS_NOT_MODIFIED:
      return "Not Modified";
    case TPEE_STATUS_TEMPORARY_REDIRECT:
      return "Temporary Redirect";
    case TPEE_STATUS_PERMANENT_REDIRECT:
      return "Permanent Redirect";
    case TPEE_STATUS_BAD_REQUEST:
      return "Bad Request";
    case TPEE_STATUS_UNAUTHORIZED:
      return "Unauthorized";
    case TPEE_STATUS_PAYMENT_REQUIRED:
      return "Payment Required";
    case TPEE_STATUS_FORBIDDEN:
      return "Forbidden";
    case TPEE_STATUS_NOT_FOUND:
      return "Not Found";
    case TPEE_STATUS_METHOD_NOT_ALLOWED:
      return "Method Not Allowed";
    case TPEE_STATUS_NOT_ACCEPTABLE:
      return "Not Acceptable";
    case TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED:
      return "Proxy Authentication Required";
    case TPEE_STATUS_REQUEST_TIMEOUT:
      return "Request Timeout";
    case TPEE_STATUS_CONFLICT:
      return "Conflict";
    case TPEE_STATUS_GONE:
      return "Gone";
    case TPEE_STATUS_LENGTH_REQUIRED:
      return "Length Required";
    case TPEE_STATUS_PRECONDITION_FAILED:
      return "Precondition Failed";
    case TPEE_STATUS_PAYLOAD_TOO_LARGE:
      return "Payload Too Large";
    case TPEE_STATUS_URI_TOO_LONG:
      return "URI Too Long";
    case TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE:
      return "Unsupported Media Type";
    case TPEE_STATUS_RANGE_NOT_SATISFIABLE:
      return "Range Not Satisfiable";
    case TPEE_STATUS_EXPECTATION_FAILED:
      return "Expectation Failed";
    case TPEE_STATUS_I_AM_A_TEAPOT:
      return "I'm a teapot";
    case TPEE_STATUS_MISDIRECTED_REQUEST:
      return "Misdirected Request";
    case TPEE_STATUS_UNPROCESSABLE_CONTENT:
      return "Unprocessable Content";
    case TPEE_STATUS_LOCKED:
      return "Locked";
    case TPEE_STATUS_FAILED_DEPENDENCY:
      return "Failed Dependency";
    case TPEE_STATUS_TOO_EARLY:
      return "Too Early";
    case TPEE_STATUS_UPGRADE_REQUIRED:
      return "Upgrade Required";
    case TPEE_STATUS_PRECONDITION_REQUIRED:
      return "Precondition Required";
    case TPEE_STATUS_TOO_MANY_REQUESTS:
      return "Too Many Requests";
    case TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:
      return "Request Header Fields Too Large";
    case TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:
      return "Unavailable For Legal Reasons";
    case TPEE_STATUS_INTERNAL_SERVER_ERROR:
      return "Internal Server Error";
    case TPEE_STATUS_NOT_IMPLEMENTED:
      return "Not Implemented";
    case TPEE_STATUS_BAD_GATEWAY:
      return "Bad Gateway";
    case TPEE_STATUS_SERVICE_UNAVAILABLE:
      return "Service Unavailable";
    case TPEE_STATUS_GATEWAY_TIMEOUT:
      return "Gateway Timeout";
    case TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED:
      return "HTTP Version Not Supported";
    case TPEE_STATUS_VARIANT_ALSO_NEGOTITATES:
      return "Variant Also Negotiates";
    case TPEE_STATUS_INSUFFICIENT_STORAGE:
      return "Insufficient Storage";
    case TPEE_STATUS_LOOP_DETECTED:
      return "Loop Detected";
    case TPEE_STATUS_NOT_EXTENDED:
      return "Not Extended";
    case TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED:
      return "Network Authentication Required";
    default:
      return NULL;
  }
}

// @impl tpee_conn_read
ssize_t tpee_conn_read(tpee_conn_t *conn, char *buffer, size_t len) {
  return sock_conn_read(conn, buffer, len);
}

// @impl tpee_conn_write
ssize_t tpee_conn_write(tpee_conn_t *conn, char *buffer, size_t len) {
  return sock_conn_write(conn, buffer, len);
}

// @impl tpee_req_header
char *tpee_req_header(tpee_req_t *req, char *key) {
  if (req->headers_len > 0) {
    for (int i = 0; i < req->headers_len; i++) {
      tpee_header_t *header = &req->headers[i];
      if (strcasecmp(header->key, key) == 0) {
        return header->value;
      }
    }
  }
  return NULL;
}

// @impl tpee_resp_header
void tpee_resp_header(tpee_resp_t *resp, char *key, char *value) {
  resp->headers = (tpee_header_t *) realloc(resp->headers, sizeof(tpee_header_t) * (resp->headers_len + 1));
  tpee_header_t *new_header = &resp->headers[resp->headers_len];
  resp->headers_len++;
  int key_len = strlen(key);
  new_header->key = (char *) malloc(sizeof(char) * (key_len + 1));
  memcpy(new_header->key, key, key_len);
  new_header->key[key_len] = '\0';
  int value_len = strlen(value);
  new_header->value = (char *) malloc(sizeof(char) * (value_len + 1));
  memcpy(new_header->value, value, value_len);
  new_header->value[value_len] = '\0';
}

// @impl tpee_resp_create
tpee_resp_t tpee_resp_create(tpee_status_t status) {
  return (tpee_resp_t) {
    .version = strdup(TPEE_VERSION),
    .status = status,
    .headers = NULL,
    .headers_len = 0,
    .body = NULL,
    .body_len = 0,
  };
}

// @impl tpee_resp_body
void tpee_resp_body(tpee_resp_t *resp, char *body, long len) {
  if (resp != NULL && body != NULL) {
    resp->body = (char *) malloc(sizeof(char) * len);
    memcpy(resp->body, body, len);
    resp->body_len = len;
  }
}

// @impl tpee_req_free
void tpee_req_free(tpee_req_t *req) {
  if (req->method != NULL) {
    free(req->method);
  }
  if (req->url != NULL) {
    free(req->url);
  }
  if (req->version != NULL) {
    free(req->version);
  }
  if (req->headers_len > 0) {
    for (int i = 0; i < req->headers_len; i++) {
      tpee_header_t *header = &req->headers[i];
      if (header->key != NULL) {
        free(header->key);
      }
      if (header->value != NULL) {
        free(header->value);
      }
    }
    free(req->headers);
  }
  if (req->body != NULL) {
    free(req->body);
  }
  if (req->ext_data != NULL) {
    free(req->ext_data);
  }
}

// @impl tpee_resp_free
void tpee_resp_free(tpee_resp_t *resp) {
  if (resp->version != NULL) {
    free(resp->version);
  }
  if (resp->headers_len > 0) {
    for (int i = 0; i < resp->headers_len; i++) {
      tpee_header_t *header = &resp->headers[i];
      if (header->key != NULL) {
        free(header->key);
      }
      if (header->value != NULL) {
        free(header->value);
      }
    }
    if (resp->headers != NULL) {
      free(resp->headers);
    }
  }
  if (resp->body != NULL) {
    free(resp->body);
  }
}

// @impl _tpee_req_read
tpee_err_t _tpee_req_read(tpee_req_t *req, tpee_conn_t *conn) {
  int len = 0;
  int ln = 0;
  int start = 0;
  char buffer[TPEE_MAX_REQUEST_HEAD_SIZE];
  *req = (tpee_req_t) {
    .conn = conn,
    .method = NULL,
    .url = NULL,
    .version = NULL,
    .headers = NULL,
    .headers_len = 0,
    .body = NULL,
    .body_len = 0,
    .ext_data = NULL,
  };
  while (true) {
    char c;
    int read = tpee_conn_read(conn, &c, 1);
    if (read == 0) {
      break;
    }
    // read timeout
    if (read == -1 || read == SSL_ERROR_SYSCALL) {
      if (errno == EWOULDBLOCK || errno == EAGAIN) {
        return (tpee_err_t) SOCK_ERR_READ_TIMEOUT;
      }
    }
    // break if too long
    if (len == TPEE_MAX_REQUEST_HEAD_SIZE) {
      return (tpee_err_t) SOCK_ERR_REQUEST_TOO_LONG;
    }
    buffer[len] = c;
    len++;
    // read head
    if (len >= 2) {
      char *slice = buffer + (len - 2);
      if (strncmp(slice, "\r\n", 2) == 0) {
        int line_len = (len - 2) - start;
        if (line_len > 0) {
          // read line
          char line[line_len + 1];
          memcpy(line, buffer + start, line_len);
          line[line_len] = '\0';
          // read method, url, and version
          if (ln == 0) {
            int arg = 0;
            int start = 0;
            for (int i = 0; i <= line_len; i++) {
              if (line[i] == ' ' || i == line_len) {
                // read method
                if (arg == 0) {
                  int method_length = i - start;
                  req->method = (char *) malloc(sizeof(char) * (method_length + 1));
                  memcpy(req->method, line + start, method_length);
                  req->method[method_length] = '\0';
                }
                // read url
                if (arg == 1) {
                  int url_length = i - start;
                  req->url = (char *) malloc(sizeof(char) * (url_length + 1));
                  memcpy(req->url, line + start, url_length);
                  req->url[url_length] = '\0';
                }
                // read version
                if (arg == 2) {
                  int version_length = i - start;
                  req->version = (char *) malloc(sizeof(char) * (version_length + 1));
                  memcpy(req->version, line + start, version_length);
                  req->version[version_length] = '\0';
                }
                start = i + 1;
                arg++;
              }
            }
          }
          // read headers
          else {
            int sep = 0;
            req->headers = (tpee_header_t *) realloc(req->headers, sizeof(tpee_header_t) * (req->headers_len + 1));
            tpee_header_t *header = &req->headers[req->headers_len];
            req->headers_len++;
            for (int i = 0; i < line_len; i++) {
              if (line[i] == ':') {
                int key_len = i;
                header->key = (char *) malloc(sizeof(char) * (key_len + 1));
                memcpy(header->key, line, key_len);
                header->key[key_len] = '\0';
                sep = i + 2;
                break;
              }
            }
            int value_len = line_len - sep;
            header->value = (char *) malloc(sizeof(char) * (value_len + 1));
            memcpy(header->value, line + sep, value_len);
            header->value[value_len] = '\0';
          }
        }
        start = len;
        ln++;
      }
    }
    // read body
    if (len >= 4) {
      char *slice = buffer + (len - 4);
      if (strncmp(slice, "\r\n\r\n", 4) == 0) {
        char *content_length = tpee_req_header(req, (char *) "Content-Length");
        if (content_length != NULL) {
          req->body_len = strtol(content_length, NULL, 10);
          if (req->body_len > 0) {
            req->body = (char *) malloc(sizeof(char) * (req->body_len + 1));
            tpee_conn_read(conn, req->body, req->body_len);
            req->body[req->body_len] = '\0';
          }
        }
        break;
      }
    }
  }
  return TPEE_ERR_OK;
}

// @impl tpee_resp_write_head
void tpee_resp_write_head(tpee_resp_t *resp, tpee_conn_t *conn) {
  tpee_conn_write(conn, resp->version, strlen(resp->version));
  tpee_conn_write(conn, (char *) " ", 1);
  char status[4];
  snprintf(status, 4, "%d", resp->status);
  tpee_conn_write(conn, status, strlen(status));
  tpee_conn_write(conn, (char *) " ", 1);
  const char *status_message = _tpee_status_str(resp->status);
  tpee_conn_write(conn, (char *) status_message, strlen(status_message));
  tpee_conn_write(conn, (char *) "\r\n", 2);
  if (resp->headers_len > 0) {
    for (int i = 0; i < resp->headers_len; i++) {
      tpee_header_t *header = &resp->headers[i];
      tpee_conn_write(conn, header->key, strlen(header->key));
      tpee_conn_write(conn, (char *) ": ", 2);
      tpee_conn_write(conn, header->value, strlen(header->value));
      tpee_conn_write(conn, (char *) "\r\n", 2);
    }
  }
  tpee_conn_write(conn, (char *) "\r\n", 2);
}

// @impl tpee_resp_write_body
void tpee_resp_write_body(tpee_resp_t *resp, tpee_conn_t *conn) {
  if (resp->body != NULL) {
    tpee_conn_write(conn, resp->body, resp->body_len);
  }
}

// @impl tpee_resp_write
void tpee_resp_write(tpee_resp_t *resp, tpee_conn_t *conn) {
  if (resp->status == __TPEE_STATUS_HANDLED) {
    return;
  }
  bool has_content_length = false;
  if (resp->body != NULL) {
    if (resp->headers_len > 0) {
      for (int i = 0; i < resp->headers_len; i++) {
        tpee_header_t *header = &resp->headers[i];
        if (strcasecmp(header->key, "Content-Length") == 0) {
          has_content_length = true;
          break;
        }
      }
    }
    if (!has_content_length) {
      char content_length[50];
      snprintf(content_length, 50, "%ld", resp->body_len);
      tpee_resp_header(resp, (char *) "Content-Length", content_length);
    }
  }
  tpee_resp_write_head(resp, conn);
  tpee_resp_write_body(resp, conn);
}

// @impl tpee_bind
tpee_err_t tpee_bind(tpee_t *self, char *hostname, int port, tpee_host_t *hosts, int hosts_len) {
  return (tpee_err_t) sock_bind(self->sock, hostname, port, hosts, hosts_len);
}

// @impl tpee_listen
tpee_err_t tpee_listen(tpee_t *self) {
  return (tpee_err_t) sock_listen(self->sock);
}

// @impl tpee_bind_listen
tpee_err_t tpee_bind_listen(tpee_t *self, char *hostname, int port) {
  return (tpee_err_t) sock_bind_listen(self->sock, hostname, port);
}

// @impl tpee_close
void tpee_close(tpee_t *self) {
  sock_close(self->sock);
}

#endif // TPEE_IMPL
