///|
/// Semantic status roles. A rendering adapter resolves them against its theme;
/// they never change an element's semantic family.
#derive(Eq, Debug)
pub(all) enum Status {
  Active
  Selected
  Warning
  Failed
}

///|
pub extend Status with Eq::{equal, not_equal}

///|
pub extend Status with @debug.Debug::{to_repr}

///|
/// A color reference. `Status` resolves to the matching property of a status
/// role in the selected theme variant; `Literal` is one CSS hex color for both
/// variants; `Variants` gives a dark and a light CSS hex color.
#derive(Eq, Debug)
pub(all) enum Paint {
  Status(Status)
  Literal(String)
  Variants(dark~ : String, light~ : String)
}

///|
pub extend Paint with Eq::{equal, not_equal}

///|
pub extend Paint with @debug.Debug::{to_repr}

///|
/// An independent visual added to an element. Decorations coexist by key.
#derive(Eq, Debug)
pub(all) enum Decoration {
  /// An outline around the element, drawn with the paint's stroke.
  Outline(Paint)
  /// A short text badge at the element's corner.
  Badge(String, Paint)
}

///|
pub extend Decoration with Eq::{equal, not_equal}

///|
pub extend Decoration with @debug.Debug::{to_repr}

///|
/// A partial override for one element. An absent property inherits: first
/// from earlier overrides of the same element, then from the baseline.
#derive(Eq, Debug)
pub struct Override {
  target : @observation.Handle
  label : String?
  shape : String?
  status : Status?
  fill : Paint?
  stroke : Paint?
  ink : Paint?
  hidden : Bool?
  collapsed : Bool?
  decorations : ReadOnlyArray[(String, Decoration)]
}

///|
pub extend Override with Eq::{equal, not_equal}

///|
pub extend Override with @debug.Debug::{to_repr}

///|
/// `label` and `shape` change layout inputs. `collapsed` folds a container;
/// `hidden` removes an element from rendering only. Decorations are keyed by a
/// name key that is unique within one override.
pub fn Override::new(
  target : @observation.Handle,
  label? : String,
  shape? : String,
  status? : Status,
  fill? : Paint,
  stroke? : Paint,
  ink? : Paint,
  hidden? : Bool,
  collapsed? : Bool,
  decorations~ : ArrayView[(String, Decoration)] = [],
) -> Override {
  {
    target,
    label,
    shape,
    status,
    fill,
    stroke,
    ink,
    hidden,
    collapsed,
    decorations: ReadOnlyArray::from_array(decorations),
  }
}

///|
/// The semantic appearance of a visual. Absent properties keep the renderer's
/// baseline for the element; `status` sets all three before explicit paints.
#derive(Eq, Debug)
pub struct Appearance {
  status : Status?
  fill : Paint?
  stroke : Paint?
  ink : Paint?
}

///|
pub extend Appearance with Eq::{equal, not_equal}

///|
pub extend Appearance with @debug.Debug::{to_repr}

///|
pub fn Appearance::new(
  status? : Status,
  fill? : Paint,
  stroke? : Paint,
  ink? : Paint,
) -> Appearance {
  { status, fill, stroke, ink, }
}

///|
/// True when the appearance changes nothing.
pub fn Appearance::is_baseline(self : Appearance) -> Bool {
  self.status is None &&
  self.fill is None &&
  self.stroke is None &&
  self.ink is None
}

///|
#derive(Eq, Debug)
pub(all) enum Role {
  /// The element itself.
  Body
  /// A decoration, by its name key.
  Decoration(String)
}

///|
pub extend Role with Eq::{equal, not_equal}

///|
pub extend Role with @debug.Debug::{to_repr}

///|
/// One visual element of a view. Several visuals can share an origin.
#derive(Eq, Debug)
pub struct Visual {
  /// Unique within the view and stable for the same model revision and role.
  key : String
  origin : @observation.Handle
  role : Role
  /// The model element, unchanged by overrides.
  element : @observation.Element
  /// The label and shape after overrides, when an override set them.
  label : String?
  shape : String?
  appearance : Appearance
  decoration : Decoration?
  hidden : Bool
  collapsed : Bool
  /// The nearest collapsed ancestor that draws this element, if any.
  collapsed_into : @observation.Handle?
}

///|
pub extend Visual with Eq::{equal, not_equal}

///|
pub extend Visual with @debug.Debug::{to_repr}

///|
/// The key of a visual: origin ordinal, role and name key.
pub fn visual_key(ordinal : Int32, role : Role) -> String {
  match role {
    Body => "\{ordinal}/body"
    Decoration(name) => "\{ordinal}/decoration/\{name}"
  }
}

///|
/// A diagram and its index: one immutable model revision. Handles that view
/// state holds come from `tree`.
pub struct Model {
  diagram : @render.Diagram
  tree : @observation.Tree
}

///|
pub fn Model::new(
  diagram : @render.Diagram,
  limits~ : @observation.IndexLimits = @observation.IndexLimits::new(),
  revision~ : Int32 = 0,
) -> Result[Model, String] {
  match @observation.Tree::of(diagram, limits~, revision~) {
    Ok(tree) => Ok({ diagram, tree, })
    Err(error) => Err(error)
  }
}

///|
/// Why a projection failed. A failed projection changes nothing.
#derive(Eq, Debug)
pub(all) enum ProjectionError {
  /// The model could not be indexed; the value is the index error code.
  Index(String)
  /// An override names an element of another model revision.
  RevisionMismatch
  /// Two visuals would have the same key.
  DuplicateKey(String)
}

///|
pub extend ProjectionError with Eq::{equal, not_equal}

///|
pub extend ProjectionError with @debug.Debug::{to_repr}

///|
pub fn ProjectionError::message(self : ProjectionError) -> String {
  match self {
    Index(code) => "The model cannot be indexed: " + code
    RevisionMismatch => "An override names an element of another model revision"
    DuplicateKey(key) => "Duplicate visual key: " + key
  }
}

///|
/// The immutable inputs that a policy sees.
pub struct Context[A, V] {
  model : Model
  state : A
  view : V
}

///|
/// A pure visual policy. Policies compose in the order the caller gives them.
pub struct Policy[A, V] {
  priv apply : (Context[A, V]) -> Array[Override]
}

///|
pub fn[A, V] Policy::new(
  apply : (Context[A, V]) -> Array[Override],
) -> Policy[A, V] {
  { apply, }
}

///|
/// A policy that decides one element at a time, in model order.
pub fn[A, V] Policy::each(
  decide : (Context[A, V], @observation.Handle, @observation.Element) -> Override?,
) -> Policy[A, V] {
  {
    apply: context => {
      let out = []
      let tree = context.model.tree
      for i in 0.. Visual? {
  for visual in self.visuals {
    if visual.key == key {
      return Some(visual)
    }
  }
  None
}

///|
/// The visuals whose origin is `handle`: its body first, then decorations.
pub fn View::visuals_of(
  self : View,
  handle : @observation.Handle,
) -> ReadOnlyArray[Visual] {
  ReadOnlyArray::from_array(
    self.visuals.iter().filter(v => v.origin == handle).to_array(),
  )
}

///|
/// True when both views have equal layout inputs, visuals and findings for
/// the same model revision. A session result equals a fresh projection.
pub fn View::equivalent(self : View, other : View) -> Bool {
  self.model.tree.owns(other.model.tree.handle(0).unwrap()) &&
  self.layout == other.layout &&
  self.visuals == other.visuals &&
  self.findings == other.findings
}

///|
/// Overrides of one element after merging in order.
priv struct Merged {
  mut label : String?
  mut shape : String?
  mut status : Status?
  mut fill : Paint?
  mut stroke : Paint?
  mut ink : Paint?
  mut hidden : Bool?
  mut collapsed : Bool?
  decorations : Array[(String, Decoration)]
}

///|
fn Merged::new() -> Merged {
  {
    label: None,
    shape: None,
    status: None,
    fill: None,
    stroke: None,
    ink: None,
    hidden: None,
    collapsed: None,
    decorations: [],
  }
}

///|
fn[T] later(current : T?, value : T?) -> T? {
  match value {
    Some(_) => value
    None => current
  }
}

///|
fn Merged::apply(self : Merged, value : Override) -> Unit {
  self.label = later(self.label, value.label)
  self.shape = later(self.shape, value.shape)
  self.status = later(self.status, value.status)
  self.fill = later(self.fill, value.fill)
  self.stroke = later(self.stroke, value.stroke)
  self.ink = later(self.ink, value.ink)
  self.hidden = later(self.hidden, value.hidden)
  self.collapsed = later(self.collapsed, value.collapsed)
  for item in value.decorations {
    match self.decorations.search_by(d => d.0 == item.0) {
      Some(i) => self.decorations[i] = item
      None => self.decorations.push(item)
    }
  }
}

///|
/// Project a model with explicit state, view state and policies. The result
/// derives only from these inputs; projection runs no action and never
/// changes the model.
pub fn[A, V] project(
  model : Model,
  state : A,
  view : V,
  policies~ : ArrayView[Policy[A, V]] = [],
  revision~ : Int32 = 0,
) -> Result[View, ProjectionError] {
  let context = { model, state, view, }
  let overrides = []
  for policy in policies {
    overrides.append((policy.apply)(context))
  }
  apply_overrides(model, overrides[:], revision~)
}

///|
/// Apply overrides in order. Use it when overrides arrive as data.
pub fn apply_overrides(
  model : Model,
  overrides : ArrayView[Override],
  revision~ : Int32 = 0,
) -> Result[View, ProjectionError] {
  let tree = model.tree
  let merged : Map[Int32, Merged] = Map([])
  for value in overrides {
    if !tree.owns(value.target) {
      return Err(RevisionMismatch)
    }
    let seen : Map[String, Bool] = Map([])
    for item in value.decorations {
      if seen.contains(item.0) {
        return Err(
          DuplicateKey(visual_key(value.target.ordinal(), Decoration(item.0))),
        )
      }
      seen[item.0] = true
    }
    let entry = match merged.get(value.target.ordinal()) {
      Some(entry) => entry
      None => {
        let entry = Merged::new()
        merged[value.target.ordinal()] = entry
        entry
      }
    }
    entry.apply(value)
  }
  // The nearest collapsed ancestor, computed top-down without recursion.
  let n = tree.length()
  let represented : Array[Int32] = Array::make(n, -1)
  // Ordinals are not pre-order, so finish ancestors before descendants.
  let order = pre_order(tree)
  for i in order {
    if tree.parent(i) is Some(parent) {
      let parent_collapsed = merged.get(parent).map(m => m.collapsed)
        is Some(Some(true))
      represented[i] = if parent_collapsed {
        parent
      } else {
        represented[parent]
      }
    }
  }
  let visuals = []
  let keys : Map[String, Bool] = Map([])
  for i in order {
    let m = merged.get(i).unwrap_or(Merged::new())
    let handle = tree.handle(i).unwrap()
    let element = tree.element(i).unwrap()
    let collapsed_into = if represented[i] >= 0 {
      tree.handle(represented[i])
    } else {
      None
    }
    let body = {
      key: visual_key(i, Body),
      origin: handle,
      role: Body,
      element,
      label: m.label,
      shape: m.shape,
      appearance: {
        status: m.status,
        fill: m.fill,
        stroke: m.stroke,
        ink: m.ink,
      },
      decoration: None,
      hidden: m.hidden.unwrap_or(false),
      collapsed: m.collapsed.unwrap_or(false),
      collapsed_into,
    }
    keys[body.key] = true
    visuals.push(body)
    for item in m.decorations {
      let (name, decoration) = item
      let key = visual_key(i, Decoration(name))
      if keys.contains(key) {
        return Err(DuplicateKey(key))
      }
      keys[key] = true
      let paint = match decoration {
        Outline(p) | Badge(_, p) => p
      }
      visuals.push({
        key,
        origin: handle,
        role: Decoration(name),
        element,
        label: None,
        shape: None,
        appearance: {
          status: None,
          fill: Some(paint),
          stroke: Some(paint),
          ink: None,
        },
        decoration: Some(decoration),
        hidden: m.hidden.unwrap_or(false),
        collapsed: false,
        collapsed_into,
      })
    }
  }
  let findings = []
  let layout = layout_input(model, merged, findings)
  Ok({
    model,
    layout,
    visuals: ReadOnlyArray::from_array(visuals),
    revision,
    findings: ReadOnlyArray::from_array(findings),
  })
}

///|
/// Ordinals in containment pre-order, without recursion.
fn pre_order(tree : @observation.Tree) -> Array[Int32] {
  let out = []
  let stack = [0]
  while stack.pop() is Some(i) {
    out.push(i)
    let children = tree.children(i)
    for j = children.length() - 1; j >= 0; j = j - 1 {
      stack.push(children[j])
    }
  }
  out
}