#include "file_server.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <fcntl.h>

#define LOGF(msg) do { FILE *__l = fopen("/tmp/peak_file_server.log", "a"); if (__l) { fprintf(__l, "%s:%d " msg "\n", __FILE__, __LINE__); fclose(__l); } } while(0)
#define LOGF_S(fmt, ...) do { FILE *__l = fopen("/tmp/peak_file_server.log", "a"); if (__l) { fprintf(__l, "%s:%d " fmt "\n", __FILE__, __LINE__, __VA_ARGS__); fclose(__l); } } while(0)

FileServer::FileServer() : running_(false), port_(0), server_fd_(-1) {}

FileServer::~FileServer() { stop(); }

bool FileServer::start(const std::string &file_path) {
  LOGF("start() acquiring lock");
  std::lock_guard<std::mutex> lock(mutex_);
  if (running_) {
    LOGF("start() already running, return false");
    return false;
  }

  file_path_ = file_path;
  LOGF_S("start() file_path='%s'", file_path.c_str());

  LOGF("start() creating socket");
  server_fd_ = socket(AF_INET, SOCK_STREAM, 0);
  if (server_fd_ < 0) {
    LOGF("start() socket failed");
    return false;
  }
  LOGF_S("start() socket fd=%d", server_fd_);

  int opt = 1;
  setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

  struct sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = 0;

  LOGF("start() binding");
  if (bind(server_fd_, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
    LOGF("start() bind failed");
    close(server_fd_);
    server_fd_ = -1;
    return false;
  }

  socklen_t addr_len = sizeof(addr);
  getsockname(server_fd_, (struct sockaddr *)&addr, &addr_len);
  port_ = ntohs(addr.sin_port);

  LOGF("start() listening");
  if (listen(server_fd_, 1) < 0) {
    LOGF("start() listen failed");
    close(server_fd_);
    server_fd_ = -1;
    return false;
  }

  running_ = true;
  LOGF_S("start() spawning thread, port=%d", port_);
  server_thread_ = std::thread(&FileServer::serve, this);
  LOGF("start() thread spawned, returning true");
  return true;
}

void FileServer::stop() {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    if (!running_)
      return;
    running_ = false;
  }
  LOGF("stop() called");
  if (server_fd_ >= 0) {
    close(server_fd_);
    server_fd_ = -1;
  }
  if (server_thread_.joinable())
    server_thread_.join();
  LOGF("stop() finished");
}

void FileServer::serve() {
  LOGF("serve() started");
  struct sockaddr_in client_addr;
  socklen_t client_len = sizeof(client_addr);

  LOGF("serve() calling accept");
  int client_fd = accept(server_fd_, (struct sockaddr *)&client_addr, &client_len);
  LOGF_S("serve() accepted client_fd=%d", client_fd);
  if (client_fd < 0) {
    running_ = false;
    LOGF("serve() accept failed");
    return;
  }

  char buf[4096];
  int total = 0;
  int n;
  while (total < (int)sizeof(buf) - 1) {
    n = recv(client_fd, buf + total, sizeof(buf) - total - 1, 0);
    if (n <= 0) break;
    total += n;
    buf[total] = 0;
    if (strstr(buf, "\r\n\r\n")) break;
  }

  struct stat st;
  if (stat(file_path_.c_str(), &st) != 0) {
    LOGF_S("serve() file not found: %s", file_path_.c_str());
    const char *resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
    send(client_fd, resp, strlen(resp), 0);
    close(client_fd);
    running_ = false;
    return;
  }
  LOGF_S("serve() file size: %ld bytes", st.st_size);

  const char *mime = "application/octet-stream";
  size_t dot = file_path_.rfind('.');
  if (dot != std::string::npos) {
    std::string ext = file_path_.substr(dot + 1);
    for (auto &c : ext) c = std::tolower(c);
    if (ext == "mp4") mime = "video/mp4";
    else if (ext == "webm") mime = "video/webm";
    else if (ext == "mkv") mime = "video/x-matroska";
    else if (ext == "avi") mime = "video/x-msvideo";
    else if (ext == "mov") mime = "video/quicktime";
    else if (ext == "png") mime = "image/png";
    else if (ext == "jpg" || ext == "jpeg") mime = "image/jpeg";
    else if (ext == "gif") mime = "image/gif";
    else if (ext == "webp") mime = "image/webp";
    else if (ext == "pdf") mime = "application/pdf";
    else if (ext == "txt") mime = "text/plain";
    else if (ext == "csv") mime = "text/csv";
    else if (ext == "json") mime = "application/json";
  }

  std::ostringstream header;
  header << "HTTP/1.1 200 OK\r\n"
         << "Content-Type: " << mime << "\r\n"
         << "Content-Length: " << st.st_size << "\r\n"
         << "Access-Control-Allow-Origin: *\r\n"
         << "Access-Control-Allow-Methods: GET, HEAD, OPTIONS\r\n"
         << "Access-Control-Allow-Headers: *\r\n"
         << "Connection: close\r\n"
         << "\r\n";
  std::string hdr = header.str();
  send(client_fd, hdr.data(), hdr.size(), 0);

  int fd = open(file_path_.c_str(), O_RDONLY);
  if (fd >= 0) {
    off_t offset = 0;
    size_t remaining = st.st_size;
    LOGF_S("serve() sendfile starting, size=%ld", st.st_size);
    while (remaining > 0) {
      ssize_t sent = sendfile(client_fd, fd, &offset, remaining);
      if (sent <= 0)
        break;
      remaining -= sent;
    }
    LOGF("serve() sendfile done");
    close(fd);
  }

  close(client_fd);
  running_ = false;
  LOGF("serve() finished");
}
