// IR visitor trait and invariant-preserving transformation hooks (plan 7.9).

///|
/// Read-only visitor over every type, record field, operation, and parameter
/// in an `IrModel`.
pub(open) trait IrVisitor {
  fn visit_type(Self, TypeDef) -> Unit = _
  fn visit_field(Self, String, FieldIR) -> Unit = _
  fn visit_operation(Self, OpIR) -> Unit = _
  fn visit_param(Self, String, ParamIR) -> Unit = _
}

///|
impl IrVisitor with fn visit_type(_self, _def) {
  ()
}

///|
impl IrVisitor with fn visit_field(_self, _owner, _field) {
  ()
}

///|
impl IrVisitor with fn visit_operation(_self, _op) {
  ()
}

///|
impl IrVisitor with fn visit_param(_self, _op_id, _param) {
  ()
}

///|
/// Walk every definition, field, operation, and parameter in deterministic
/// order, invoking `visitor`.
pub fn[V : IrVisitor] IrModel::walk(self : IrModel, visitor : V) -> Unit {
  for def in self.defs {
    visitor.visit_type(def)
    match def {
      Record(r) =>
        for f in r.fields {
          visitor.visit_field(r.name, f)
        }
      TaggedEnum(t) =>
        for v in t.variants {
          match v.payload {
            Fields(fs) =>
              for f in fs {
                visitor.visit_field("\{t.name}::\{v.name}", f)
              }
            _ => ()
          }
        }
      _ => ()
    }
  }
  for op in self.operations {
    visitor.visit_operation(op)
    for p in op.params {
      visitor.visit_param(op.operation_id, p)
    }
  }
}

///|
/// Closure-based IR transformation hooks for library consumers.
/// Returning `None` from a hook filters out the item; returning `Some(x)`
/// replaces it.
pub(all) struct IrHooks {
  map_def : ((TypeDef) -> TypeDef?)?
  map_field : ((String, FieldIR) -> FieldIR?)?
  map_operation : ((OpIR) -> OpIR?)?
}

///|
/// No-op `IrHooks` with all hook callbacks unset.
pub fn IrHooks::empty() -> IrHooks {
  { map_def: None, map_field: None, map_operation: None, }
}

///|
fn rewrite_def_names(def : TypeDef, renames : Map[String, String]) -> TypeDef {
  match def {
    Record(r) =>
      Record({
        ..r,
        fields: r.fields.map(f => {
          ..f,
          type_: rewrite_ft_names(f.type_, renames),
        }),
      })
    TaggedEnum(t) =>
      TaggedEnum({
        ..t,
        variants: t.variants.map(v => {
          let payload = match v.payload {
            Unit => VariantPayload::Unit
            NewType(ft) =>
              VariantPayload::NewType(rewrite_ft_names(ft, renames))
            Fields(fs) =>
              VariantPayload::Fields(
                fs.map(f => { ..f, type_: rewrite_ft_names(f.type_, renames), }),
              )
          }
          { ..v, payload, }
        }),
      })
    UntaggedEnum(u) =>
      UntaggedEnum({
        ..u,
        variants: u.variants.map(v => {
          ..v,
          type_: rewrite_ft_names(v.type_, renames),
        }),
      })
    Alias(a) => Alias({ ..a, target: rewrite_ft_names(a.target, renames), })
    StringEnum(_) => def
  }
}

///|
fn rewrite_op_names(op : OpIR, renames : Map[String, String]) -> OpIR {
  let params = op.params.map(p => {
    ..p,
    type_: rewrite_ft_names(p.type_, renames),
  })
  let body = match op.body {
    Json(ft, content_type~, required~, docs~) =>
      BodyIR::Json(
        rewrite_ft_names(ft, renames),
        content_type~,
        required~,
        docs~,
      )
    Multipart(parts, required~, docs~) =>
      BodyIR::Multipart(
        parts.map(pt => { ..pt, type_: rewrite_ft_names(pt.type_, renames), }),
        required~,
        docs~,
      )
    FormUrlEncoded(parts, required~, docs~) =>
      BodyIR::FormUrlEncoded(
        parts.map(pt => { ..pt, type_: rewrite_ft_names(pt.type_, renames), }),
        required~,
        docs~,
      )
    Text(..) | Binary(..) | NoBody => op.body
  }
  let responses = op.responses.map(r => {
    let type_ = match r.type_ {
      Some(ft) => Some(rewrite_ft_names(ft, renames))
      None => None
    }
    let body_kind = match r.body_kind {
      Json(ft) => ResponseBodyKind::Json(rewrite_ft_names(ft, renames))
      Stream(Ndjson(ft)) =>
        ResponseBodyKind::Stream(
          StreamKind::Ndjson(rewrite_ft_names(ft, renames)),
        )
      Other(Some(ft)) =>
        ResponseBodyKind::Other(Some(rewrite_ft_names(ft, renames)))
      Empty | Binary | Text | Stream(Sse) | Stream(Binary) | Other(None) =>
        r.body_kind
    }
    let headers = r.headers.map(h => {
      ..h,
      type_: rewrite_ft_names(h.type_, renames),
    })
    { ..r, type_, body_kind, headers, }
  })
  { ..op, params, body, responses, }
}

///|
/// Produce a new `IrModel` by applying `hooks` while preserving all internal
/// indexes (`types` map, `component_names`, `Named(...)` references on rename,
/// and tag `groups`).
pub fn IrModel::transform(self : IrModel, hooks : IrHooks) -> IrModel {
  let raw_new_defs : Array[TypeDef] = []
  let seen_names : Map[String, Unit] = Map([])
  let renames : Map[String, String] = Map([])
  for raw_def in self.defs {
    let old_name = raw_def.name()
    let field_mapped : TypeDef = match hooks.map_field {
      None => raw_def
      Some(f_hook) =>
        match raw_def {
          Record(r) => {
            let fields : Array[FieldIR] = []
            for f in r.fields {
              match f_hook(r.name, f) {
                Some(nf) => fields.push(nf)
                None => ()
              }
            }
            Record({ ..r, fields, })
          }
          TaggedEnum(t) => {
            let variants : Array[VariantIR] = []
            for v in t.variants {
              let payload = match v.payload {
                Fields(fs) => {
                  let out_fs : Array[FieldIR] = []
                  for f in fs {
                    match f_hook("\{t.name}::\{v.name}", f) {
                      Some(nf) => out_fs.push(nf)
                      None => ()
                    }
                  }
                  if out_fs.is_empty() {
                    VariantPayload::Unit
                  } else {
                    VariantPayload::Fields(out_fs)
                  }
                }
                other => other
              }
              variants.push({ ..v, payload, })
            }
            TaggedEnum({ ..t, variants, })
          }
          other => other
        }
    }
    let final_opt = match hooks.map_def {
      Some(d_hook) => d_hook(field_mapped)
      None => Some(field_mapped)
    }
    match final_opt {
      Some(d) => {
        let new_name = d.name()
        if new_name != old_name {
          renames[old_name] = new_name
        }
        if !seen_names.contains(new_name) {
          seen_names[new_name] = ()
          raw_new_defs.push(d)
        }
      }
      None => ()
    }
  }
  let new_defs : Array[TypeDef] = []
  let new_types : Map[String, TypeDef] = Map([])
  for d in raw_new_defs {
    let rewritten = if renames.is_empty() {
      d
    } else {
      rewrite_def_names(d, renames)
    }
    new_types[rewritten.name()] = rewritten
    new_defs.push(rewritten)
  }
  let new_ops : Array[OpIR] = []
  for raw_op in self.operations {
    let final_opt = match hooks.map_operation {
      Some(o_hook) => o_hook(raw_op)
      None => Some(raw_op)
    }
    match final_opt {
      Some(op) =>
        new_ops.push(
          if renames.is_empty() {
            op
          } else {
            rewrite_op_names(op, renames)
          },
        )
      None => ()
    }
  }
  let new_component_names : Map[String, String] = Map([])
  for comp, mapped in self.component_names {
    let target = renames.get(mapped).unwrap_or(mapped)
    if new_types.contains(target) {
      new_component_names[comp] = target
    }
  }
  // Rebuild deterministic groups from transformed operations
  let group_map : Map[String, Array[String]] = Map([])
  let group_order : Array[String] = []
  for op in new_ops {
    match group_map.get(op.group) {
      Some(ids) => ids.push(op.operation_id)
      None => {
        group_order.push(op.group)
        group_map[op.group] = [op.operation_id]
      }
    }
  }
  let new_groups : Array[(String, Array[String])] = []
  for g in group_order {
    match group_map.get(g) {
      Some(ids) => new_groups.push((g, ids))
      None => ()
    }
  }
  {
    ..self,
    defs: new_defs,
    types: new_types,
    component_names: new_component_names,
    operations: new_ops,
    groups: new_groups,
  }
}