///|
/// Upstream error or invalid caption returned during the vision stage.
pub(all) struct VisionFailure {
  status : Int32
  body : Bytes
  headers : Array[(String, String)]
}

///|
priv struct CacheEntry {
  caption : String
  expires_at : Int64
  mut last_used_at : Int64
}

///|
priv struct LogRecord {
  key : String
  caption : String
  expires_at : Int64
  last_used_at : Int64
}

///|
/// Shared slot for coalescing concurrent requests for the same inline image.
pub struct PendingSlot {
  priv cond : @cond_var.Cond
  priv mut outcome : Result[String, VisionFailure]?
}

///|
/// Wait until the owner fiber finishes captioning this image.
pub async fn PendingSlot::wait(
  self : PendingSlot,
) -> Result[String, VisionFailure] {
  while self.outcome is None {
    self.cond.wait()
  }
  match self.outcome {
    Some(res) => res
    None =>
      Err({
        status: 502,
        body: b"{\"error\":{\"type\":\"vision_error\",\"message\":\"In-flight caption cancelled.\"}}",
        headers: [("Content-Type", "application/json")],
      })
  }
}

///|
/// Result of probing the caption store before calling the vision model.
pub(all) enum LookupOutcome {
  Hit(String)
  Wait(PendingSlot)
  Owner(PendingSlot)
}

///|
let seg_header_size : Int64 = 16L

///|
let rec_header_size : Int32 = 8

///|
let flush_interval_ms : Int32 = 200

///|
/// Minimum interval (seconds) between disk-persisted LRU timestamp touches for
/// repeated hits on the same cached image. In-memory `last_used_at` always
/// updates immediately.
let touch_persist_interval_sec : Int64 = 60L

///|
/// Persistent, O(1) in-memory caption store backed by an async 2-segment
/// rotating append-only disk log (`captions.0.log` / `captions.1.log`) and
/// zero-lock `@cond_var` concurrent in-flight deduplication.
pub struct CaptionStore {
  priv dir : String
  priv disk_enabled : Bool
  priv ttl_sec : Int64
  priv max_entries : Int32
  priv worker_id : Int32
  priv workers : Int32
  priv entries : Map[String, CacheEntry]
  priv pending_flights : Map[String, PendingSlot]
  priv mut pending_writes : Array[LogRecord]
  priv mut active_file : @fs.File?
  priv mut active_seg : Int32
  priv mut active_offset : Int64
  priv mut active_records : Int32
  priv mut gen : UInt64
  priv flush_mu : @async.Mutex
  priv mut hits : Int64
  priv mut misses : Int64
  priv mut coalesced : Int64
}

///|
pub fn now_unix_sec() -> Int64 {
  (@env.now() / 1000UL).reinterpret_as_int64()
}

///|
/// Pure in-memory store (used for `--no-cache` and unit tests).
pub fn CaptionStore::memory(
  ttl_sec~ : Int64 = 2_592_000L,
  max_entries~ : Int32 = 10_000,
) -> CaptionStore {
  {
    dir: "",
    disk_enabled: false,
    ttl_sec,
    max_entries,
    worker_id: 0,
    workers: 1,
    entries: Map([]),
    pending_flights: Map([]),
    pending_writes: [],
    active_file: None,
    active_seg: 0,
    active_offset: 0L,
    active_records: 0,
    gen: 0UL,
    flush_mu: @async.Mutex(),
    hits: 0L,
    misses: 0L,
    coalesced: 0L,
  }
}

///|
fn segment_path_for(
  dir : String,
  worker_id : Int32,
  workers : Int32,
  seg : Int32,
) -> String {
  let sep = if dir.contains("\\") { "\\" } else { "/" }
  if workers > 1 {
    dir +
    sep +
    "captions-w" +
    worker_id.to_string() +
    "." +
    seg.to_string() +
    ".log"
  } else {
    dir + sep + "captions." + seg.to_string() + ".log"
  }
}

///|
fn CaptionStore::seg_path(self : CaptionStore, seg : Int32) -> String {
  segment_path_for(self.dir, self.worker_id, self.workers, seg)
}

///|
fn write_i32_le_buf(buf : @buffer.Buffer, v : Int32) -> Unit {
  let u = v.reinterpret_as_uint()
  buf.write_byte((u & 0xffU).to_byte())
  buf.write_byte(((u >> 8) & 0xffU).to_byte())
  buf.write_byte(((u >> 16) & 0xffU).to_byte())
  buf.write_byte(((u >> 24) & 0xffU).to_byte())
}

///|
fn write_u64_le_buf(buf : @buffer.Buffer, u : UInt64) -> Unit {
  for shift = 0; shift < 64; shift = shift + 8 {
    buf.write_byte(((u >> shift) & 0xffUL).to_byte())
  }
}

///|
fn read_i32_le(b : Bytes, pos : Int32) -> Int32 {
  let u = b[pos].to_uint() |
    (b[pos + 1].to_uint() << 8) |
    (b[pos + 2].to_uint() << 16) |
    (b[pos + 3].to_uint() << 24)
  u.reinterpret_as_int()
}

///|
fn read_u64_le(b : Bytes, pos : Int32) -> UInt64 {
  let mut u = 0UL
  for k = 0; k < 8; k = k + 1 {
    u = u | (b[pos + k].to_uint64() << (k * 8))
  }
  u
}

///|
fn make_segment_header(gen : UInt64) -> Bytes {
  let buf = @buffer.Buffer(capacity=16)
  buf.write_bytesview(b"NVP1")
  write_i32_le_buf(buf, 1)
  write_u64_le_buf(buf, gen)
  buf.to_bytes()
}

///|
fn encode_record(buf : @buffer.Buffer, rec : LogRecord) -> Unit {
  let key_b = @utf8.encode(rec.key)
  let cap_b = @utf8.encode(rec.caption)
  let payload_len = 8 + 8 + 4 + key_b.length() + 4 + cap_b.length()
  buf.write_bytesview(b"CAP1")
  write_i32_le_buf(buf, payload_len)
  write_u64_le_buf(buf, rec.expires_at.reinterpret_as_uint64())
  write_u64_le_buf(buf, rec.last_used_at.reinterpret_as_uint64())
  write_i32_le_buf(buf, key_b.length())
  buf.write_bytesview(key_b[:])
  write_i32_le_buf(buf, cap_b.length())
  buf.write_bytesview(cap_b[:])
}

///|
/// Parse a segment's header and valid records up to any truncated tail.
/// Returns `(gen, valid_end_offset, record_count, parsed_records)` or `None` if header invalid.
fn parse_segment_bytes(
  raw : Bytes,
) -> (UInt64, Int64, Int32, Array[LogRecord])? {
  if raw.length() < 16 {
    return None
  }
  if raw[0] != b'N' || raw[1] != b'V' || raw[2] != b'P' || raw[3] != b'1' {
    return None
  }
  let ver = read_i32_le(raw, 4)
  if ver != 1 {
    return None
  }
  let gen = read_u64_le(raw, 8)
  let total = raw.length()
  let mut pos = 16
  let mut count = 0
  let records : Array[LogRecord] = []
  while pos + rec_header_size <= total {
    if raw[pos] != b'C' ||
      raw[pos + 1] != b'A' ||
      raw[pos + 2] != b'P' ||
      raw[pos + 3] != b'1' {
      break
    }
    let plen = read_i32_le(raw, pos + 4)
    if plen < 24 || pos + rec_header_size + plen > total {
      // Truncated tail after crash: stop cleanly at `pos`.
      break
    }
    let p = pos + rec_header_size
    let expires_at = read_u64_le(raw, p).reinterpret_as_int64()
    let last_used_at = read_u64_le(raw, p + 8).reinterpret_as_int64()
    let klen = read_i32_le(raw, p + 16)
    if klen < 0 || 20 + klen + 4 > plen {
      break
    }
    let clen = read_i32_le(raw, p + 20 + klen)
    if clen < 0 || 24 + klen + clen != plen {
      break
    }
    let key_opt : String? = Some(@utf8.decode(raw[p + 20:p + 20 + klen])) catch {
      _ => None
    }
    let cap_opt : String? = Some(
      @utf8.decode(raw[p + 24 + klen:p + 24 + klen + clen]),
    ) catch {
      _ => None
    }
    match (key_opt, cap_opt) {
      (Some(key), Some(caption)) => {
        records.push({ key, caption, expires_at, last_used_at, })
        pos += rec_header_size + plen
        count += 1
      }
      _ => break
    }
  }
  Some((gen, pos.to_int64(), count, records))
}

///|
/// Open a persistent `CaptionStore` in `dir`, replaying existing segment logs
/// and recovering cleanly from any truncated tail. Falls back to memory mode
/// if `dir` is unwritable.
pub async fn CaptionStore::open(
  dir : String,
  ttl_sec~ : Int64 = 2_592_000L,
  max_entries~ : Int32 = 10_000,
  worker_id~ : Int32 = 0,
  workers~ : Int32 = 1,
  now_sec~ : Int64 = now_unix_sec(),
) -> CaptionStore {
  if dir.is_empty() {
    return CaptionStore::memory(ttl_sec~, max_entries~)
  }
  let mkdir_ok = try {
    @fs.mkdir(dir, recursive=true, allow_exist=true)
    true
  } catch {
    _ => false
  }
  if !mkdir_ok {
    return CaptionStore::memory(ttl_sec~, max_entries~)
  }
  let loaded : Array[(Int32, UInt64, Int64, Int32, Array[LogRecord])] = []
  for seg = 0; seg < 2; seg = seg + 1 {
    let p = segment_path_for(dir, worker_id, workers, seg)
    let raw_opt : Bytes? = Some(@fs.read_file(p).binary()) catch { _ => None }
    match raw_opt {
      Some(raw) =>
        match parse_segment_bytes(raw) {
          Some((g, valid_off, cnt, recs)) =>
            loaded.push((seg, g, valid_off, cnt, recs))
          None => ()
        }
      None => ()
    }
  }
  loaded.sort_by((a, b) => {
    if a.1 < b.1 {
      -1
    } else if a.1 > b.1 {
      1
    } else {
      0
    }
  })
  let entries : Map[String, CacheEntry] = Map([])
  for item in loaded {
    for rec in item.4 {
      if rec.expires_at > now_sec {
        entries[rec.key] = {
          caption: rec.caption,
          expires_at: rec.expires_at,
          last_used_at: rec.last_used_at,
        }
      } else {
        entries.remove(rec.key)
      }
    }
  }
  let store : CaptionStore = {
    dir,
    disk_enabled: true,
    ttl_sec,
    max_entries,
    worker_id,
    workers,
    entries,
    pending_flights: Map([]),
    pending_writes: [],
    active_file: None,
    active_seg: 0,
    active_offset: seg_header_size,
    active_records: 0,
    gen: 1UL,
    flush_mu: @async.Mutex(),
    hits: 0L,
    misses: 0L,
    coalesced: 0L,
  }
  store.evict_if_needed(now_sec)
  if loaded.length() > 0 {
    let newest = loaded[loaded.length() - 1]
    let seg = newest.0
    let gen = newest.1
    let valid_off = newest.2
    let cnt = newest.3
    let path = store.seg_path(seg)
    let f_opt : @fs.File? = Some(
      @fs.open(path, mode=WriteOnly, create_mode=OpenOrCreate),
    ) catch {
      _ => None
    }
    match f_opt {
      Some(f) => {
        store.active_file = Some(f)
        store.active_seg = seg
        store.active_offset = valid_off
        store.active_records = cnt
        store.gen = gen
        return store
      }
      None => return CaptionStore::memory(ttl_sec~, max_entries~)
    }
  }
  // Initialize segment 0 from scratch.
  let p0 = store.seg_path(0)
  let f_opt : @fs.File? = try {
    let f = @fs.open(p0, mode=WriteOnly, create_mode=CreateOrTruncate)
    let hdr = make_segment_header(1UL)
    f.write_at(hdr[:], position=0L)
    Some(f)
  } catch {
    _ => None
  }
  match f_opt {
    Some(f) => {
      store.active_file = Some(f)
      store.active_seg = 0
      store.active_offset = seg_header_size
      store.active_records = 0
      store.gen = 1UL
      store
    }
    None => CaptionStore::memory(ttl_sec~, max_entries~)
  }
}

///|
pub fn CaptionStore::size(self : CaptionStore) -> Int32 {
  self.entries.length()
}

///|
pub fn CaptionStore::stats(self : CaptionStore) -> (Int32, Int64, Int64, Int64) {
  (self.entries.length(), self.hits, self.misses, self.coalesced)
}

///|
pub fn CaptionStore::is_persistent(self : CaptionStore) -> Bool {
  self.disk_enabled && self.active_file is Some(_)
}

///|
fn CaptionStore::evict_if_needed(self : CaptionStore, now_sec : Int64) -> Unit {
  if self.entries.length() <= self.max_entries {
    return
  }
  let expired : Array[String] = []
  for k, v in self.entries {
    if v.expires_at <= now_sec {
      expired.push(k)
    }
  }
  for k in expired {
    self.entries.remove(k)
  }
  let excess = self.entries.length() - self.max_entries
  if excess <= 0 {
    return
  }
  let candidates : Array[(String, Int64)] = Array(
    capacity=self.entries.length(),
  )
  for k, v in self.entries {
    candidates.push((k, v.last_used_at))
  }
  candidates.sort_by((a, b) => {
    if a.1 < b.1 {
      -1
    } else if a.1 > b.1 {
      1
    } else {
      0
    }
  })
  for i = 0; i < excess; i = i + 1 {
    self.entries.remove(candidates[i].0)
  }
}

///|
/// O(1) cache lookup without in-flight registration (useful for tests).
pub fn CaptionStore::get(
  self : CaptionStore,
  key : String,
  now_sec~ : Int64 = now_unix_sec(),
) -> String? {
  match self.entries.get(key) {
    Some(entry) =>
      if entry.expires_at <= now_sec {
        self.entries.remove(key)
        None
      } else {
        let prev = entry.last_used_at
        entry.last_used_at = now_sec
        if self.disk_enabled && now_sec - prev >= touch_persist_interval_sec {
          self.pending_writes.push({
            key,
            caption: entry.caption,
            expires_at: entry.expires_at,
            last_used_at: now_sec,
          })
        }
        Some(entry.caption)
      }
    None => None
  }
}

///|
/// Insert or update a caption directly in memory and queue async persistence.
pub fn CaptionStore::put(
  self : CaptionStore,
  key : String,
  caption : String,
  now_sec~ : Int64 = now_unix_sec(),
) -> Unit {
  let expires_at = now_sec + self.ttl_sec
  self.entries[key] = { caption, expires_at, last_used_at: now_sec, }
  self.evict_if_needed(now_sec)
  if self.disk_enabled {
    self.pending_writes.push({
      key,
      caption,
      expires_at,
      last_used_at: now_sec,
    })
  }
}

///|
/// Probe cache for `key`, or register/join an in-flight request slot so
/// concurrent identical `data:` images share a single upstream vision call.
pub fn CaptionStore::begin_lookup(
  self : CaptionStore,
  key : String,
  now_sec~ : Int64 = now_unix_sec(),
) -> LookupOutcome {
  match self.get(key, now_sec~) {
    Some(caption) => {
      self.hits += 1L
      Hit(caption)
    }
    None =>
      match self.pending_flights.get(key) {
        Some(slot) => {
          self.coalesced += 1L
          Wait(slot)
        }
        None => {
          self.misses += 1L
          let slot : PendingSlot = { cond: @cond_var.Cond(), outcome: None, }
          self.pending_flights[key] = slot
          Owner(slot)
        }
      }
  }
}

///|
/// Complete an `Owner` slot, storing `caption` on `Ok` and waking all waiters.
pub fn CaptionStore::finish_lookup(
  self : CaptionStore,
  key : String,
  slot : PendingSlot,
  result : Result[String, VisionFailure],
  now_sec~ : Int64 = now_unix_sec(),
) -> Unit {
  self.pending_flights.remove(key)
  match result {
    Ok(caption) => self.put(key, caption, now_sec~)
    Err(_) => ()
  }
  slot.outcome = Some(result)
  slot.cond.broadcast()
}

///|
fn CaptionStore::compaction_threshold(self : CaptionStore) -> Int32 {
  let doubled = self.max_entries * 2
  if doubled < 256 {
    256
  } else {
    doubled
  }
}

///|
async fn CaptionStore::compact_to_inactive(
  self : CaptionStore,
  now_sec~ : Int64 = now_unix_sec(),
) -> Unit {
  let other = 1 - self.active_seg
  let next_gen = self.gen + 1UL
  let buf = @buffer.Buffer(capacity=4096)
  buf.write_bytesview(make_segment_header(next_gen)[:])
  let mut written_count = 0
  for k, v in self.entries {
    if v.expires_at > now_sec {
      encode_record(buf, {
        key: k,
        caption: v.caption,
        expires_at: v.expires_at,
        last_used_at: v.last_used_at,
      })
      written_count += 1
    }
  }
  let bytes = buf.to_bytes()
  let other_path = self.seg_path(other)
  let new_file_opt : @fs.File? = try {
    let f = @fs.open(other_path, mode=WriteOnly, create_mode=CreateOrTruncate)
    f.write_at(bytes[:], position=0L)
    Some(f)
  } catch {
    e => {
      println("[cache] segment compaction failed: " + e.to_string())
      None
    }
  }
  match new_file_opt {
    Some(new_f) => {
      let old_seg = self.active_seg
      match self.active_file {
        Some(old_f) => old_f.close()
        None => ()
      }
      self.active_file = Some(new_f)
      self.active_seg = other
      self.active_offset = bytes.length().to_int64()
      self.active_records = written_count
      self.gen = next_gen
      // Truncate/remove old segment so stale records do not waste space.
      @fs.remove(self.seg_path(old_seg), allow_missing=true) catch {
        _ => ()
      }
    }
    None => ()
  }
}

///|
/// Flush queued cache writes to the active segment off the event loop.
pub async fn CaptionStore::flush_pending(self : CaptionStore) -> Unit {
  if !self.disk_enabled || self.pending_writes.length() == 0 {
    return
  }
  self.flush_mu.acquire()
  defer self.flush_mu.release()
  if !self.disk_enabled || self.pending_writes.length() == 0 {
    return
  }
  let batch = self.pending_writes
  self.pending_writes = []
  // If segment has grown past 2x capacity, write a fresh compacted snapshot
  // of `self.entries` directly to the other segment instead of appending.
  if self.active_records + batch.length() > self.compaction_threshold() {
    self.compact_to_inactive()
    return
  }
  let buf = @buffer.Buffer(capacity=batch.length() * 256)
  for rec in batch {
    encode_record(buf, rec)
  }
  let data = buf.to_bytes()
  match self.active_file {
    Some(f) => {
      let ok = try {
        f.write_at(data[:], position=self.active_offset)
        true
      } catch {
        e => {
          println("[cache] append write failed: " + e.to_string())
          false
        }
      }
      if ok {
        self.active_offset += data.length().to_int64()
        self.active_records += batch.length()
      }
    }
    None => ()
  }
}

///|
/// Background flusher loop: coalesces disk writes every ~200ms off the hot path.
pub async fn CaptionStore::run_flusher(self : CaptionStore) -> Unit {
  if !self.disk_enabled {
    return
  }
  for ;; {
    @async.sleep(flush_interval_ms)
    self.flush_pending()
  }
}

///|
/// Flush pending records and close the underlying segment file handle.
pub async fn CaptionStore::close(self : CaptionStore) -> Unit {
  self.flush_pending()
  self.flush_mu.acquire()
  defer self.flush_mu.release()
  match self.active_file {
    Some(f) => {
      f.close()
      self.active_file = None
    }
    None => ()
  }
}