#ifndef USE_CURL
#define _POSIX_C_SOURCE 200809L
#include "http_client.h"
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

static char *xstrndup2(const char *s, size_t n) { char *p = malloc(n + 1); if (!p) return NULL; memcpy(p, s, n); p[n] = 0; return p; }
static int append(char **b, size_t *len, size_t *cap, const char *p, size_t n) {
    if (*len + n + 1 > *cap) { size_t nc = (*len + n + 1) * 2 + 512; char *q = realloc(*b, nc); if (!q) return -1; *b = q; *cap = nc; }
    memcpy(*b + *len, p, n); *len += n; (*b)[*len] = 0; return 0;
}

void http_response_free(http_response *r) { if (!r) return; free(r->headers); free(r->body); r->headers = r->body = NULL; r->status = 0; }

char *http_header_value(const char *headers, const char *name) {
    if (!headers || !name) return NULL;
    size_t nl = strlen(name);
    const char *p = headers;
    while (*p) {
        const char *e = strstr(p, "\r\n"); if (!e) e = p + strlen(p);
        if ((size_t)(e - p) > nl && !strncasecmp(p, name, nl) && p[nl] == ':') {
            const char *v = p + nl + 1;
            while (v < e && (*v == ' ' || *v == '\t')) v++;
            while (e > v && (e[-1] == ' ' || e[-1] == '\t')) e--;
            return xstrndup2(v, (size_t)(e - v));
        }
        if (!*e) break;
        p = e + 2;
    }
    return NULL;
}

static int parse_url(const char *url, char **host, char **port, char **path) {
    const char *p = strstr(url, "://"); if (!p) return -1;
    p += 3;
    const char *slash = strchr(p, '/');
    const char *hend = slash ? slash : p + strlen(p);
    const char *colon = memchr(p, ':', (size_t)(hend - p));
    if (colon) { *host = xstrndup2(p, (size_t)(colon - p)); *port = xstrndup2(colon + 1, (size_t)(hend - colon - 1)); }
    else { *host = xstrndup2(p, (size_t)(hend - p)); *port = strdup("80"); }
    *path = strdup(slash ? slash : "/");
    return (*host && *port && *path) ? 0 : -1;
}

static int connect_unix(const char *path) {
    int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return -1;
    struct sockaddr_un sa; memset(&sa, 0, sizeof sa); sa.sun_family = AF_UNIX;
    if (strlen(path) >= sizeof sa.sun_path) { close(fd); return -1; }
    strcpy(sa.sun_path, path);
    if (connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) { close(fd); return -1; }
    return fd;
}

static int connect_tcp(const char *host, const char *port) {
    struct addrinfo hints, *res = NULL, *rp; memset(&hints, 0, sizeof hints);
    hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC;
    if (getaddrinfo(host, port, &hints, &res)) return -1;
    int fd = -1;
    for (rp = res; rp; rp = rp->ai_next) {
        fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (fd < 0) continue;
        if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0) break;
        close(fd); fd = -1;
    }
    freeaddrinfo(res); return fd;
}

static int write_all(int fd, const char *p, size_t n) {
    while (n) { ssize_t w = write(fd, p, n); if (w < 0 && errno == EINTR) continue; if (w <= 0) return -1; p += w; n -= (size_t)w; }
    return 0;
}

int http_request(const char *method, const char *url, const char *unix_socket,
                 const char *extra_headers, const char *body, http_response *out) {
    memset(out, 0, sizeof *out);
    char *host = NULL, *port = NULL, *path = NULL;
    if (parse_url(url, &host, &port, &path)) goto fail;
    int fd = (unix_socket && *unix_socket) ? connect_unix(unix_socket) : connect_tcp(host, port);
    if (fd < 0) goto fail;

    size_t body_len = body ? strlen(body) : 0;
    char head[2048];
    int hn = snprintf(head, sizeof head,
        "%s %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\nContent-Length: %zu\r\n%s\r\n",
        method, path, host, body_len, extra_headers ? extra_headers : "");
    if (hn < 0 || (size_t)hn >= sizeof head) { close(fd); goto fail; }
    if (write_all(fd, head, (size_t)hn) || (body_len && write_all(fd, body, body_len))) { close(fd); goto fail; }

    char *buf = NULL; size_t len = 0, cap = 0; char tmp[4096]; ssize_t r;
    while ((r = read(fd, tmp, sizeof tmp)) > 0) if (append(&buf, &len, &cap, tmp, (size_t)r)) { close(fd); goto fail; }
    close(fd);
    if (!buf) goto fail;
    char *sep = strstr(buf, "\r\n\r\n"); if (!sep) { free(buf); goto fail; }
    *sep = 0; char *bodyp = sep + 4;
    long status = 0; sscanf(buf, "HTTP/%*s %ld", &status);
    out->status = status; out->headers = strdup(buf); out->body = strdup(bodyp);
    free(buf); free(host); free(port); free(path);
    return (out->headers && out->body) ? 0 : -1;
fail:
    free(host); free(port); free(path); http_response_free(out); return -1;
}
#endif
