// Evaluator types — EvalResult, Dereference, EntityStore, EvalError.
// References:
//   Rust: cedar-policy-core/src/evaluator.rs
//   Go:   cedar-go/internal/eval/

// ---------------------------------------------------------------------------
// EvalResult — unified partial evaluation return type
// ---------------------------------------------------------------------------

///|
/// Result of evaluating an expression.
/// Value(v) means a concrete value was produced.
/// Residual(e) means the expression could not be reduced and is returned as-is.
pub(all) enum EvalResult {
  Value(@ast.Value)
  Residual(@ast.Expr)
} derive(Debug, Eq)

// ---------------------------------------------------------------------------
// Dereference — entity lookup result
// ---------------------------------------------------------------------------

///|
/// Result of looking up an entity in the store.
pub(all) enum Dereference {
  Data(@ast.Entity)
  NoSuchEntity
  Residual(@ast.Expr)
} derive(Debug, Eq)

// ---------------------------------------------------------------------------
// EntityStore trait — pluggable entity storage
// ---------------------------------------------------------------------------

///|
/// Pluggable entity storage. Implement this trait to provide entity lookups
/// from any backing store (in-memory Map, database, cache, etc.).
pub trait EntityStore {
  fn get_entity(Self, @ast.EntityUID) -> @ast.Entity?
}

///|
/// In-memory entity store backed by a Map.
pub(all) struct MapEntityStore {
  entities : Map[@ast.EntityUID, @ast.Entity]
} derive(Debug, Eq)

///|
/// MapEntityStore implements EntityStore.
pub impl EntityStore for MapEntityStore with fn get_entity(
  self : MapEntityStore,
  uid : @ast.EntityUID,
) -> @ast.Entity? {
  self.entities.get(uid)
}

///|
/// JSON serialization as a plain array of entities. Each entity is self-describing
/// (includes its uid), so the array format naturally captures the key-value mapping.
/// Format: [ { uid: {...}, attrs: {...}, tags: {...}, parents: [...] }, ... ]
pub impl ToJson for MapEntityStore with fn to_json(self) -> Json {
  let arr : Array[Json] = []
  for _, entity in self.entities {
    arr.push(entity.to_json())
  }
  Json::array(arr)
}

///|
/// JSON deserialization from a plain array of entities. The uid is extracted
/// from each entity and used as the map key.
pub impl FromJson for MapEntityStore with fn from_json(
  json : Json,
  path : @json.JsonPath,
) -> MapEntityStore raise @json.JsonDecodeError {
  match json {
    Json::Array(entries) => {
      let entities : Map[@ast.EntityUID, @ast.Entity] = Map([])
      for i = 0; i < entries.length(); i = i + 1 {
        let entry_path = path.add_index(i)
        let entity = @ast.Entity::from_json(entries[i], entry_path)
        entities.set(entity.uid, entity)
      }
      MapEntityStore::{ entities, }
    }
    _ => {
      let payload : (@json.JsonPath, String) = (
        path, "expected JSON array of entities",
      )
      raise @json.JsonDecodeError(payload)
    }
  }
}

///|
/// Create an empty MapEntityStore.
pub fn new_map_store() -> MapEntityStore {
  MapEntityStore::{ entities: Map([]) }
}

// ---------------------------------------------------------------------------
// EvalError
// ---------------------------------------------------------------------------

///|
/// Errors that can occur during expression evaluation.
pub(all) suberror EvalError {
  TypeMismatch(String)
  IntegerOverflow
  EntityNotFound(String)
  InvalidOperator(String)
  ExtensionNotSupported(String)
  SlotNotSupported
} derive(Debug, Eq)

// ---------------------------------------------------------------------------
// Request — PARC slots + context
// ---------------------------------------------------------------------------

///|
/// A PARC slot: either a known EntityUID (concrete eval) or a typed Unknown (partial eval).
pub(all) enum EntityUIDEntry {
  Concrete(@ast.EntityUID)
  Unknown(@ast.EntityType)
} derive(Debug, Eq)

///|
/// Helper: construct a concrete EntityUIDEntry.
pub fn concrete_uid(type_ : String, id : String) -> EntityUIDEntry {
  Concrete(@ast.EntityUID::{ type_, id })
}

///|
/// Request context — three states matching Rust's CPE:
/// - Concrete(Value::Record(...)): fully known context
/// - Unknown(Expr): entirely unknown (e.g., Expr::Unknown("context", None))
/// - Partial(Expr): partially known, containing an Expr::Record where
///   individual fields may be Expr::Unknown nodes.
pub(all) enum Context {
  Concrete(@ast.Value)
  Unknown(@ast.Expr)
  Partial(@ast.Expr)
} derive(Debug, Eq)

///|
/// The PARC authorization request.
pub(all) struct Request {
  principal : EntityUIDEntry
  action : EntityUIDEntry
  resource : EntityUIDEntry
  context : Context
} derive(Debug, Eq)