#include "UFP.h"

#include <stdio.h>

using namespace ufp_detail;

namespace {

enum : uint8_t {
  MSG_ENUM = 0x01,
  MSG_DESCRIBE_FUNC = 0x02,
  MSG_DESCRIBE_EVENT = 0x03,
  MSG_CALL = 0x04,
  MSG_SUBSCRIBE = 0x05,
  MSG_UNSUBSCRIBE = 0x06,
  MSG_PING = 0x07,
  MSG_NOTIFY = 0x7F,
  MSG_ERROR = 0xFF,
  RSP = 0x80,
};

const uint16_t CONN_CHECK_MS = 100;

// Some cores' USB CDC operator bool() calls delay(10): don't poll it there.
#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_MEGAAVR)
const bool CONN_CHECK_ENABLED = false;
#else
const bool CONN_CHECK_ENABLED = true;
#endif

// COBS-decode in place; returns the decoded length or -1 if invalid.
int cobsDecode(uint8_t* buf, uint16_t n) {
  uint16_t i = 0, o = 0;
  while (i < n) {
    uint8_t code = buf[i];
    if (code == 0 || (uint32_t)i + code > n) return -1;
    for (uint8_t k = 1; k < code; k++) buf[o++] = buf[i + k];
    i += code;
    if (code < 0xFF && i < n) buf[o++] = 0;
  }
  return o;
}

// Token `index` of a comma-separated list "name[:unit[:desc]], ...".
// Returns false if there is no such token or its name is empty.
bool specToken(const char* spec, uint8_t index, const char* part[3], uint8_t len[3]) {
  const char* p = spec ? spec : "";
  for (uint8_t i = 0; i < index; i++) {
    p = strchr(p, ',');
    if (!p) return false;
    p++;
  }
  const char* end = strchr(p, ',');
  if (!end) end = p + strlen(p);
  for (uint8_t k = 0; k < 3; k++) {
    // the description (last part) may contain ':'
    const char* stop = end;
    if (k < 2) {
      const char* c = (const char*)memchr(p, ':', end - p);
      if (c) stop = c;
    }
    const char* a = p;
    const char* b = stop;
    while (a < b && isspace((unsigned char)*a)) a++;
    while (b > a && isspace((unsigned char)b[-1])) b--;
    part[k] = a;
    len[k] = (uint8_t)((b - a) > 255 ? 255 : (b - a));
    p = stop < end ? stop + 1 : end;
  }
  return len[0] > 0;
}

}  // namespace

// ---------------------------------------------------------------------------
// CRCs
// ---------------------------------------------------------------------------

uint16_t ufp_detail::crc16(uint16_t crc, uint8_t b) {
  crc ^= (uint16_t)b << 8;
  for (uint8_t i = 0; i < 8; i++) crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1;
  return crc;
}

uint32_t ufp_detail::crc32(uint32_t crc, uint8_t b) {
  crc ^= b;
  for (uint8_t i = 0; i < 8; i++) crc = (crc & 1) ? (crc >> 1) ^ 0xEDB88320UL : crc >> 1;
  return crc;
}

// ---------------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------------

void Writer::toBuffer(uint8_t* buf, uint16_t limit) {
  mode_ = BUFFER;
  buf_ = buf;
  limit_ = limit;
  count_ = 0;
  tooLarge_ = noRoom_ = false;
}

void Writer::toCrc32() {
  mode_ = CRC32;
  limit_ = 0xFFFF;
  count_ = 0;
  crc_ = 0xFFFFFFFFUL;
  tooLarge_ = noRoom_ = false;
}

void Writer::toFrame(Ring* ring, uint16_t limit, uint16_t reserve) {
  mode_ = FRAME;
  ring_ = ring;
  limit_ = limit;
  reserve_ = reserve;
  count_ = 0;
  tooLarge_ = noRoom_ = false;
  crc_ = 0xFFFF;
  startHead_ = ring->head;
  startUsed_ = ring->used;
  codeIdx_ = ring->head;
  code_ = 1;
  push(0);  // placeholder for the first COBS code byte
}

void Writer::push(uint8_t b) {
  if (noRoom_) return;
  if ((uint32_t)ring_->used + reserve_ >= ring_->size) {
    noRoom_ = true;
    return;
  }
  ring_->buf[ring_->head] = b;
  if (++ring_->head == ring_->size) ring_->head = 0;
  ring_->used++;
}

void Writer::cobs(uint8_t b) {
  if (b) {
    push(b);
    if (++code_ < 0xFF) return;
  }
  if (!noRoom_) ring_->buf[codeIdx_] = code_;
  codeIdx_ = ring_->head;
  code_ = 1;
  push(0);
}

void Writer::put(uint8_t b) {
  if (count_ >= limit_) {
    tooLarge_ = true;
    return;
  }
  count_++;
  switch (mode_) {
    case BUFFER:
      buf_[count_ - 1] = b;
      break;
    case CRC32:
      crc_ = ufp_detail::crc32(crc_, b);
      break;
    case FRAME:
      crc_ = ufp_detail::crc16((uint16_t)crc_, b);
      cobs(b);
      break;
  }
}

bool Writer::finish() {
  if (mode_ != FRAME) return !tooLarge_;
  uint16_t crc = (uint16_t)crc_;
  cobs(crc & 0xFF);
  cobs(crc >> 8);
  if (!noRoom_) ring_->buf[codeIdx_] = code_;
  push(0);  // delimiter
  if (noRoom_ || tooLarge_ || count_ < 2) {
    abort();
    return false;
  }
  return true;
}

void Writer::abort() {
  if (mode_ != FRAME) return;
  ring_->head = startHead_;
  ring_->used = startUsed_;
}

// ---------------------------------------------------------------------------
// UFPBase
// ---------------------------------------------------------------------------

UFPBase::UFPBase(const char* name, uint16_t maxPayload, uint8_t* rx, uint16_t rxCap, uint8_t* tx,
                 uint16_t txCap, uint8_t* scratch, FuncEntry* funcs, uint8_t maxFunc,
                 EventEntry* events, uint8_t maxEvt)
    : name_(name ? name : ""),
      port_(0),
      conn_(0),
      connected_(false),
      lastConnCheck_(0),
      maxPayload_(maxPayload),
      maxInflight_(1),
      rx_(rx),
      scratch_(scratch),
      rxCap_(rxCap),
      rxLen_(0),
      rxReady_(false),
      rxSkip_(false),
      funcs_(funcs),
      events_(events),
      maxFunc_(maxFunc),
      maxEvt_(maxEvt),
      nfunc_(0),
      nevt_(0),
      session_(false),
      handling_(false),
      subs_(0),
      nseq_(0),
      bootId_(0),
      bootIdSet_(false),
      hash_(0),
      hashValid_(false),
      failCode_(0),
      logEvent_(0xFF),
      dropped_(0),
      frameErrors_(0) {
  ring_.buf = tx;
  ring_.size = txCap;
  ring_.head = ring_.tail = ring_.used = 0;
  failMsg_[0] = 0;
}

void UFPBase::beginStream(Stream* s, ConnFn conn) {
  port_ = s;
  conn_ = CONN_CHECK_ENABLED ? conn : 0;
  connected_ = conn_ ? conn_(port_) : true;
  if (!bootIdSet_) {
#if defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
    bootId_ = rp2040.hwrand32();
#elif defined(ESP32)
    bootId_ = esp_random();
#else
    bootId_ = 0;  // completed with micros() at the first ENUM
#endif
  }
  schemaHash();
}

void UFPBase::endSession() {
  session_ = false;
  subs_ = 0;
  nseq_ = 0;
  ring_.head = ring_.tail = ring_.used = 0;
  rxLen_ = 0;
  rxReady_ = rxSkip_ = false;
}

void UFPBase::loop() {
  if (!port_ || handling_) return;
  if (conn_) {
    uint32_t now = millis();
    if (now - lastConnCheck_ >= CONN_CHECK_MS) {
      lastConnCheck_ = now;
      bool c = conn_(port_);
      if (connected_ && !c) endSession();  // host closed the port
      connected_ = c;
    }
  }
  flush();
  tryHandle();
  readInput();
  if (tryHandle()) flush();
}

void UFPBase::flush() {
  while (ring_.used) {
    int room = port_->availableForWrite();
    if (room <= 0) return;
    uint16_t chunk = ring_.size - ring_.tail;
    if (chunk > ring_.used) chunk = ring_.used;
    if ((uint16_t)room < chunk) chunk = room;
    size_t k = port_->write(ring_.buf + ring_.tail, chunk);
    if (k == 0) return;
    ring_.tail = (ring_.tail + k) % ring_.size;
    ring_.used -= k;
  }
}

void UFPBase::readInput() {
  while (!rxReady_ && port_->available() > 0) {
    int c = port_->read();
    if (c < 0) return;
    if (c != 0) {
      if (rxLen_ < rxCap_) {
        rx_[rxLen_++] = (uint8_t)c;
      } else {
        rxSkip_ = true;  // oversized: drop until the next delimiter
        rxLen_ = 0;
      }
      continue;
    }
    // delimiter
    if (rxSkip_) {
      rxSkip_ = false;
      rxLen_ = 0;
      frameErrors_++;
      continue;
    }
    if (rxLen_ == 0) continue;
    int n = cobsDecode(rx_, rxLen_);
    if (n < 4) {
      frameErrors_++;
      rxLen_ = 0;
      continue;
    }
    uint16_t crc = 0xFFFF;
    for (int i = 0; i < n - 2; i++) crc = crc16(crc, rx_[i]);
    if (crc != (uint16_t)(rx_[n - 2] | (rx_[n - 1] << 8))) {
      frameErrors_++;
      rxLen_ = 0;
      continue;
    }
    rxLen_ = n - 2;
    rxReady_ = true;
  }
}

bool UFPBase::tryHandle() {
  if (!rxReady_) return false;
  // responses are sent in order: wait until a full-size frame fits
  if ((uint32_t)ring_.size - ring_.used <= frameMax()) return false;
  handle(rx_, rxLen_);
  rxReady_ = false;
  rxLen_ = 0;
  return true;
}

void UFPBase::fail(uint8_t code, const char* msg) {
  failCode_ = code ? code : (uint8_t)UFP_ERR_UNSPECIFIED;
  strncpy(failMsg_, msg ? msg : "", sizeof(failMsg_) - 1);
  failMsg_[sizeof(failMsg_) - 1] = 0;
}

bool UFPBase::subscribed(uint8_t id) const {
  return session_ && id < nevt_ && (subs_ & (1UL << id));
}

void UFPBase::handle(const uint8_t* p, uint16_t n) {
  uint8_t mt = p[0], seq = p[1];
  Reader r(p + 2, n - 2);
  Writer w;
  w.toBuffer(scratch_, maxPayload_);
  w.u8(mt | RSP);
  w.u8(seq);
  uint8_t err = UFP_OK;
  const char* msg = "";
  uint8_t id = 0;
  handling_ = true;

  switch (mt) {
    case MSG_ENUM:
      if (!r.atEnd()) {
        err = UFP_ERR_MALFORMED;
        break;
      }
      if (!bootIdSet_) {
        bootId_ ^= micros();  // time of the first ENUM varies between boots
        bootIdSet_ = true;
      }
      session_ = true;
      subs_ = 0;
      nseq_ = 0;
      w.u8(UFP_PROTOCOL_VERSION);
      w.u8(nfunc_);
      w.u8(nevt_);
      w.u16(maxPayload_);
      w.u8(maxInflight_);
      w.u32(bootId_);
      w.u32(schemaHash());
      w.pstr(name_);
      break;

    case MSG_DESCRIBE_FUNC:
    case MSG_DESCRIBE_EVENT:
    case MSG_SUBSCRIBE:
    case MSG_UNSUBSCRIBE:
      if (!r.get(&id, 1)) {
        err = UFP_ERR_MALFORMED;
      } else if (mt == MSG_DESCRIBE_FUNC ? id >= nfunc_ : id >= nevt_) {
        err = mt == MSG_DESCRIBE_FUNC ? UFP_ERR_UNKNOWN_FUNC : UFP_ERR_UNKNOWN_EVENT;
        msg = mt == MSG_DESCRIBE_FUNC ? "unknown function" : "unknown event";
      } else if (!r.atEnd()) {
        err = UFP_ERR_MALFORMED;
      } else if (mt == MSG_DESCRIBE_FUNC) {
        describeFunction(w, id);
      } else if (mt == MSG_DESCRIBE_EVENT) {
        describeEvent(w, id);
      } else {
        if (mt == MSG_SUBSCRIBE)
          subs_ |= 1UL << id;
        else
          subs_ &= ~(1UL << id);
        w.u8(id);
      }
      break;

    case MSG_CALL:
      if (!r.get(&id, 1)) {
        err = UFP_ERR_MALFORMED;
      } else if (id >= nfunc_) {
        err = UFP_ERR_UNKNOWN_FUNC;
        msg = "unknown function";
      } else {
        w.u8(id);
        failCode_ = 0;
        err = funcs_[id].invoke(funcs_[id].fn, r, w);
        if (!err && failCode_) {
          err = failCode_;
          msg = failMsg_;
        }
      }
      break;

    case MSG_PING:
      if (r.remaining() > 8) {
        err = UFP_ERR_MALFORMED;
        msg = "ping data longer than 8 bytes";
      } else {
        w.write(p + 2, n - 2);
      }
      break;

    default:
      err = UFP_ERR_UNKNOWN_MSG;
      break;
  }
  handling_ = false;

  if (!err && w.tooLarge()) {
    err = UFP_ERR_TOO_LARGE;
    msg = "response too large";
  }
  if (err == UFP_ERR_MALFORMED && !*msg) msg = "malformed request";
  if (err) {
    w.toBuffer(scratch_, maxPayload_);
    w.u8(MSG_ERROR);
    w.u8(seq);
    w.u8(mt);
    w.u8(err);
    size_t len = strlen(msg);
    if (len > (size_t)maxPayload_ - 5) len = maxPayload_ - 5;
    w.pstr(msg, len);
  }
  uint16_t len = w.count();
  Writer f;
  f.toFrame(&ring_, maxPayload_, 0);
  f.write(scratch_, len);
  f.finish();
}

void UFPBase::entry(Writer& w, const TypeInfo& t, const char* spec, uint8_t index,
                    const char* fallback) {
  w.u8(t.tag);
  if ((t.tag & C_MASK) == C_FIXED) w.u16(t.n);
  const char* part[3];
  uint8_t len[3];
  if (specToken(spec, index, part, len)) {
    w.pstr(part[0], len[0]);  // name
    w.pstr(part[2], len[2]);  // description
    w.pstr(part[1], len[1]);  // unit
  } else {
    char name[12];
    int k = snprintf(name, sizeof(name), "%s%u", fallback, index);
    w.pstr(name, k);
    w.u8(0);
    w.u8(0);
  }
}

bool UFPBase::describeFunction(Writer& w, uint8_t id) {
  const FuncEntry& f = funcs_[id];
  w.u8(id);
  w.pstr(f.name);
  w.pstr(f.desc);
  uint8_t nargs = 0, nrets = f.ret.tag ? 1 : 0;
  for (uint8_t i = 0; i < f.nparams; i++) f.params[i].out ? nrets++ : nargs++;
  w.u8(nargs);
  for (uint8_t i = 0, k = 0; i < f.nparams; i++)
    if (!f.params[i].out) entry(w, f.params[i], f.args, k++, "arg");
  w.u8(nrets);
  uint8_t k = 0;
  if (f.ret.tag) entry(w, f.ret, f.rets, k++, "ret");
  for (uint8_t i = 0; i < f.nparams; i++)
    if (f.params[i].out) entry(w, f.params[i], f.rets, k++, "ret");
  return !w.tooLarge();
}

bool UFPBase::describeEvent(Writer& w, uint8_t id) {
  const EventEntry& e = events_[id];
  w.u8(id);
  w.pstr(e.name);
  w.pstr(e.desc);
  w.u8(e.n);
  for (uint8_t i = 0; i < e.n; i++) entry(w, e.types[i], e.fields, i, "field");
  return !w.tooLarge();
}

uint32_t UFPBase::schemaHash() {
  if (!hashValid_) {
    Writer w;
    w.toCrc32();
    for (uint8_t i = 0; i < nfunc_; i++) describeFunction(w, i);
    for (uint8_t i = 0; i < nevt_; i++) describeEvent(w, i);
    // CRC32 mode has no length limit beyond 64 KiB in total; tables never get close
    hash_ = w.crc32();
    hashValid_ = true;
  }
  return hash_;
}

uint8_t UFPBase::addEvent(const char* name, const char* fields, const char* desc,
                          const TypeInfo* types, uint8_t n) {
  if (nevt_ >= maxEvt_) return 0xFF;
  EventEntry& e = events_[nevt_];
  e.name = name;
  e.fields = fields ? fields : "";
  e.desc = desc ? desc : "";
  e.types = types;
  e.n = n;
  hashValid_ = false;
  return nevt_++;
}

bool UFPBase::notifyBegin(uint8_t id, Writer& w) {
  if (!port_ || !subscribed(id)) return false;
  // keep room for the response being built, if any
  w.toFrame(&ring_, maxPayload_, handling_ ? frameMax() : 0);
  w.u8(MSG_NOTIFY);
  w.u8(nseq_++);  // counts dropped notifications too (docs.md 10.6)
  w.u8(id);
  return true;
}

bool UFPBase::notifyEnd(Writer& w) {
  if (w.finish()) return true;
  dropped_++;
  return false;
}

bool UFPBase::enableLog() {
  if (logEvent_ != 0xFF) return true;
  static const TypeInfo types[] = {{T_U8, 0, 0}, {T_STR, 0, 0}};
  logEvent_ = addEvent("log", "level, msg", "Device log output (0 error, 1 warn, 2 info, 3 debug)",
                       types, 2);
  return logEvent_ != 0xFF;
}

bool UFPBase::log(uint8_t level, const char* msg) {
  if (logEvent_ == 0xFF) return false;
  Writer w;
  if (!notifyBegin(logEvent_, w)) return false;
  size_t len = strlen(msg);
  if (len > (size_t)maxPayload_ - 6) len = maxPayload_ - 6;  // header 3 + level 1 + length 2
  w.u8(level);
  w.u16((uint16_t)len);
  w.write(msg, (uint16_t)len);
  return notifyEnd(w);
}

bool UFPBase::logPrintf(uint8_t level, const char* fmt, ...) {
  if (!subscribed(logEvent_)) return false;
  char buf[96];
  va_list ap;
  va_start(ap, fmt);
  vsnprintf(buf, sizeof(buf), fmt, ap);
  va_end(ap);
  return log(level, buf);
}
