// viewer-model.h: per-model state and global server state
//
// Holds the gguf context (metadata), ggml context (tensor structs),
// mmap handle, precomputed tensor entries, and slice stats cache.
// Shared by the HTTP routes and the main entry point.

#pragma once

#include "viewer-io.h"
#include "viewer-tensor.h"

#include <ggml-cpp.h>
#include <gguf.h>

#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

namespace fs = std::filesystem;

// per-model state (loaded on first access, cached)
struct model_state {
  std::string model_path;
  std::string relative_path;

  // gguf metadata context (KV pairs, tensor descriptors)
  gguf_context_ptr gguf_ctx;

  // ggml context with tensor structs (shapes, types, no data allocated)
  ggml_context_ptr tensor_ctx;

  // memory-mapped file for tensor data access
  mapped_file mmap;

  // precomputed tensor entries (one per tensor, with layout + absolute offsets)
  std::vector<tensor_entry> tensors;

  // tensor name to index in tensors[]
  std::unordered_map<std::string, size_t> tensor_index;

  // slice stats cache: [tensor_index][slice_index]
  mutable std::mutex stats_mutex;
  mutable std::vector<std::vector<slice_stats>> stats_cache;
};

// global server state
struct server_state {
  fs::path root;
  std::mutex mutex;
  std::unordered_map<std::string, std::shared_ptr<model_state>> models;
};
