/* =============================================================================
 * http_client.c -- speak HTTP by hand and print the raw reply
 * =============================================================================
 *
 * [Idea]
 *   HTTP is text. A browser is a large program, but the conversation it has
 *   with a server is simple enough to write in a dozen lines: connect, send a
 *   request line plus headers plus a blank line, then read the reply. Printing
 *   the reply EXACTLY as it arrives -- status line, headers, blank line, body --
 *   is the best way to see that "the Web" is a protocol, not magic.
 *
 * [What it answers]
 *   - What does a client actually send?
 *   - What does a response look like before a browser renders it?
 *   - Why does the blank line matter, and what is Content-length for?
 *
 * Usage:   ./http_client [host] [port] [path]
 *          defaults: localhost 15214 /
 *
 * By default it talks to this lecture's own tiny_server on the loopback
 * interface, so `make run` needs no network and prints the same bytes every
 * time. Point it at a real site to see a real server's headers.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

int main(int argc, char **argv)
{
    const char *host = (argc > 1) ? argv[1] : "localhost";
    const char *port = (argc > 2) ? argv[2] : "15214";
    const char *path = (argc > 3) ? argv[3] : "/";

    /* 1. Connect (retrying briefly in case the demo's server is still starting). */
    int fd = -1;
    for (int attempt = 1; attempt <= 20; attempt++) {
        fd = open_clientfd(host, port);
        if (fd >= 0) break;
        usleep(50 * 1000);
    }
    if (fd < 0) {
        fprintf(stderr, "http_client: cannot connect to %s:%s\n", host, port);
        return 1;
    }

    /* 2. Build and send the request.
     *    - the REQUEST LINE names the method, the path and the version;
     *    - "Host:" is required by HTTP/1.1 and polite in 1.0 (one machine can
     *      serve many sites, so the server needs to know which was asked for);
     *    - "Connection: close" asks the server to close when done, which makes
     *      "read until EOF" a correct way to get the whole body;
     *    - the BLANK LINE ends the headers. Forgetting it means the server
     *      waits forever for more headers -- the classic beginner hang.
     */
    char req[MAXLINE];
    int reqlen = snprintf(req, sizeof(req),
                          "GET %s HTTP/1.0\r\n"
                          "Host: %s\r\n"
                          "User-Agent: 15213-http-client/1.0\r\n"
                          "Connection: close\r\n"
                          "\r\n",
                          path, host);

    printf("=== the request we send (%d bytes) ===\n", reqlen);
    fputs(req, stdout);                 /* show it verbatim, CRLFs and all */
    printf("=== end of request ===\n\n");

    if (rio_writen(fd, req, (size_t)reqlen) != reqlen) {
        perror("rio_writen"); close(fd); return 1;
    }

    /* 3. Read the response. The head is lines of text; we print them as they
     *    come and stop at the blank line. */
    rio_t rio;
    rio_readinitb(&rio, fd);

    char line[MAXLINE];
    ssize_t n = rio_readlineb(&rio, line, MAXLINE);
    if (n <= 0) {
        fprintf(stderr, "http_client: no response\n"); close(fd); return 1;
    }
    printf("=== the response status line ===\n%s", line);

    printf("=== the response headers ===\n");
    long content_length = -1;
    int nhdrs = 0;
    while ((n = rio_readlineb(&rio, line, MAXLINE)) > 0) {
        if (!strcmp(line, "\r\n") || !strcmp(line, "\n"))
            break;                      /* the blank line: body starts next */
        printf("%s", line);
        nhdrs++;
        /* Content-length tells us exactly how many body bytes to expect. */
        if (!strncasecmp(line, "Content-length:", 15))
            content_length = strtol(line + 15, NULL, 10);
    }
    printf("=== (%d header(s); blank line seen -> body follows) ===\n\n", nhdrs);

    /* 4. Read the body. Two correct strategies:
     *      - if Content-length is known, read exactly that many bytes;
     *      - otherwise read until EOF (valid because we said Connection: close).
     *    Both need RIO: a socket hands over data in arbitrary pieces. */
    printf("=== the response body ===\n");
    size_t total = 0;
    char body[MAXLINE];
    if (content_length >= 0) {
        size_t want = (size_t)content_length;
        while (total < want) {
            size_t chunk = want - total;
            if (chunk > sizeof(body)) chunk = sizeof(body);
            n = rio_readnb(&rio, body, chunk);
            if (n <= 0) break;
            fwrite(body, 1, (size_t)n, stdout);
            total += (size_t)n;
        }
    } else {
        while ((n = rio_readnb(&rio, body, sizeof(body))) > 0) {
            fwrite(body, 1, (size_t)n, stdout);
            total += (size_t)n;
        }
    }
    printf("=== end of body (%zu bytes", total);
    if (content_length >= 0)
        printf(", Content-length said %ld: %s", content_length,
               total == (size_t)content_length ? "match" : "MISMATCH");
    printf(") ===\n");

    close(fd);

    printf("\nObservations\n------------\n");
    printf("- the entire exchange is TEXT: a request line, headers, a blank\n");
    printf("  line, then (in the reply) a body. No binary framing, no magic.\n");
    printf("- the BLANK LINE is the delimiter that ends the headers. Omit it and\n");
    printf("  the server waits for more headers and the client appears to hang.\n");
    printf("- Content-length let us read exactly the right number of body bytes\n");
    printf("  and then verify it (%zu bytes read).\n", total);
    printf("- the body was read with RIO because a socket delivers a STREAM in\n");
    printf("  arbitrary pieces -- Lecture 18's short counts, on the network.\n");
    return 0;
}
