// Pure MoonBit JSON-LD 1.1 serializer and parser built over
// `moonbitlang/core/json`.

///|
/// Typed parse error for JSON-LD documents.
#derive(Eq, Debug)
pub suberror JsonLdParseError {
  InvalidJson(detail~ : String)
  InvalidStructure(detail~ : String)
  InvalidTerm(detail~ : String)
}

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

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

///|
fn compact_iri_jsonld(iri : Iri, prefixes : Array[(String, Iri)]) -> String {
  let raw = iri.as_str()
  for entry in prefixes {
    let (prefix, ns) = entry
    let base = ns.as_str()
    if raw.has_prefix(base) {
      let local_part = raw[base.length():].to_owned()
      if is_pn_local_safe(local_part) {
        return "\{prefix}:\{local_part}"
      }
    }
  }
  raw
}

///|
fn object_to_jsonld(obj : ObjectTerm, prefixes : Array[(String, Iri)]) -> Json {
  match obj {
    IriObject(iri) =>
      Json::object({ "@id": Json::string(compact_iri_jsonld(iri, prefixes)) })
    BlankObject(id) => Json::object({ "@id": Json::string("_:\{id.as_str()}") })
    LiteralObject(lit) =>
      match lit {
        Plain(v) => Json::string(v)
        LangString(value~, lang~) =>
          Json::object({
            "@value": Json::string(value),
            "@language": Json::string(lang.as_str()),
          })
        Typed(value~, datatype~) =>
          if datatype == Iri::xsd_string() {
            Json::string(value)
          } else {
            Json::object({
              "@value": Json::string(value),
              "@type": Json::string(compact_iri_jsonld(datatype, prefixes)),
            })
          }
      }
  }
}

///|
/// Serializes RDF triples into pretty-printed JSON-LD 1.1 with `@context` and
/// `@graph` (or a single top-level node when exactly one subject is present).
pub fn serialize_jsonld(
  triples : ReadOnlyArray[Triple],
  prefixes~ : Array[(String, Iri)] = standard_prefixes(),
) -> String {
  let sorted : Array[Triple] = triples.iter().collect()
  sorted.sort_by((a, b) => a.compare(b))
  let ctx_map : Map[String, Json] = Map([])
  for entry in prefixes {
    ctx_map[entry.0] = Json::string(entry.1.as_str())
  }
  let nodes : Array[Json] = []
  let mut i = 0
  let total = sorted.length()
  while i < total {
    let subj = sorted[i].subject()
    let node : Map[String, Json] = Map([])
    node["@id"] = Json::string(
      match subj {
        IriSubject(iri) => compact_iri_jsonld(iri, prefixes)
        BlankSubject(id) => "_:\{id.as_str()}"
      },
    )
    let types : Array[Json] = []
    while i < total && sorted[i].subject() == subj {
      let pred = sorted[i].predicate()
      if pred == Iri::rdf_type() {
        while i < total &&
              sorted[i].subject() == subj &&
              sorted[i].predicate() == pred {
          match sorted[i].object() {
            IriObject(t_iri) =>
              types.push(Json::string(compact_iri_jsonld(t_iri, prefixes)))
            other => types.push(object_to_jsonld(other, prefixes))
          }
          i += 1
        }
      } else {
        let key = compact_iri_jsonld(pred, prefixes)
        let values : Array[Json] = []
        while i < total &&
              sorted[i].subject() == subj &&
              sorted[i].predicate() == pred {
          values.push(object_to_jsonld(sorted[i].object(), prefixes))
          i += 1
        }
        node[key] = if values.length() == 1 {
          values[0]
        } else {
          Json::array(values)
        }
      }
    }
    if types.length() == 1 {
      node["@type"] = types[0]
    } else if types.length() > 1 {
      node["@type"] = Json::array(types)
    }
    nodes.push(Json::object(node))
  }
  let root : Map[String, Json] = Map([])
  root["@context"] = Json::object(ctx_map)
  if nodes.length() == 1 {
    match nodes[0] {
      Object(single) =>
        for k, v in single {
          root[k] = v
        }
      _ => ()
    }
  } else {
    root["@graph"] = Json::array(nodes)
  }
  Json::object(root).stringify(indent=2)
}

///|
fn expand_jsonld_iri(
  raw : String,
  ctx : Map[String, String],
) -> Iri raise JsonLdParseError {
  if raw.find(":") is Some(colon) {
    let prefix = raw[:colon].to_owned()
    let rest = raw[colon + 1:].to_owned()
    if ctx.get(prefix) is Some(ns) && !rest.has_prefix("//") {
      let full = ns + rest
      return Iri(full) catch {
        _ => raise InvalidTerm(detail="Invalid expanded IRI \{full}")
      }
    }
  }
  Iri(raw) catch {
    _ => raise InvalidTerm(detail="Invalid IRI \{raw}")
  }
}

///|
fn parse_jsonld_subject(
  raw : String,
  ctx : Map[String, String],
) -> Subject raise JsonLdParseError {
  if raw.has_prefix("_:") {
    let label = raw[2:].to_owned()
    let bnode = BlankNodeId(label) catch {
      _ => raise InvalidTerm(detail="Invalid blank node \{raw}")
    }
    BlankSubject(bnode)
  } else {
    IriSubject(expand_jsonld_iri(raw, ctx))
  }
}

///|
fn parse_jsonld_object(
  val : Json,
  ctx : Map[String, String],
) -> ObjectTerm raise JsonLdParseError {
  match val {
    String(s) => LiteralObject(Plain(s))
    True => LiteralObject(Typed(value="true", datatype=Iri::xsd_boolean()))
    False => LiteralObject(Typed(value="false", datatype=Iri::xsd_boolean()))
    Number(n, ..) =>
      LiteralObject(Typed(value=n.to_string(), datatype=Iri::xsd_integer()))
    Object(obj) =>
      if obj.get("@id") is Some(String(id_str)) {
        if id_str.has_prefix("_:") {
          let label = id_str[2:].to_owned()
          let bnode = BlankNodeId(label) catch {
            _ => raise InvalidTerm(detail="Invalid blank node \{id_str}")
          }
          BlankObject(bnode)
        } else {
          IriObject(expand_jsonld_iri(id_str, ctx))
        }
      } else if obj.get("@value") is Some(String(v)) {
        if obj.get("@language") is Some(String(raw_lang)) {
          let lang = LangTag(raw_lang) catch {
            _ => raise InvalidTerm(detail="Invalid language tag \{raw_lang}")
          }
          LiteralObject(LangString(value=v, lang~))
        } else if obj.get("@type") is Some(String(raw_dt)) {
          let datatype = expand_jsonld_iri(raw_dt, ctx)
          if datatype == Iri::xsd_string() {
            LiteralObject(Plain(v))
          } else {
            LiteralObject(Typed(value=v, datatype~))
          }
        } else {
          LiteralObject(Plain(v))
        }
      } else {
        raise InvalidStructure(
          detail="JSON-LD object value must contain '@id' or '@value'",
        )
      }
    _ => raise InvalidStructure(detail="Unsupported JSON-LD object value kind")
  }
}

///|
fn parse_jsonld_node(
  node : Map[String, Json],
  ctx : Map[String, String],
  graph : GraphName,
  quads : Array[Quad],
) -> Unit raise JsonLdParseError {
  guard node.get("@id") is Some(String(id_str)) else {
    raise InvalidStructure(detail="JSON-LD node is missing string '@id'")
  }
  let subject = parse_jsonld_subject(id_str, ctx)
  for key, val in node {
    if key == "@context" || key == "@id" || key == "@graph" {
      continue
    }
    if key == "@type" {
      match val {
        String(t) =>
          quads.push(
            Quad(
              graph~,
              subject~,
              predicate=Iri::rdf_type(),
              object=IriObject(expand_jsonld_iri(t, ctx)),
            ),
          )
        Array(arr) =>
          for item in arr {
            guard item is String(t) else {
              raise InvalidStructure(detail="'@type' array must hold strings")
            }
            quads.push(
              Quad(
                graph~,
                subject~,
                predicate=Iri::rdf_type(),
                object=IriObject(expand_jsonld_iri(t, ctx)),
              ),
            )
          }
        _ =>
          raise InvalidStructure(
            detail="'@type' must be a string or string array",
          )
      }
      continue
    }
    let predicate = expand_jsonld_iri(key, ctx)
    match val {
      Array(items) =>
        for item in items {
          let object = parse_jsonld_object(item, ctx)
          quads.push(Quad(graph~, subject~, predicate~, object~))
        }
      single => {
        let object = parse_jsonld_object(single, ctx)
        quads.push(Quad(graph~, subject~, predicate~, object~))
      }
    }
  }
}

///|
/// Parses a JSON-LD 1.1 document into an immutable `Dataset` in `graph`.
pub fn parse_jsonld(
  input : String,
  graph~ : GraphName = DefaultGraph,
) -> Dataset raise JsonLdParseError {
  let doc = @json.parse(input) catch {
    err => raise InvalidJson(detail="\{err}")
  }
  guard doc is Object(root) else {
    raise InvalidStructure(detail="JSON-LD root must be a JSON object")
  }
  let ctx : Map[String, String] = Map([])
  if root.get("@context") is Some(Object(ctx_obj)) {
    for k, v in ctx_obj {
      if v is String(ns) {
        ctx[k] = ns
      }
    }
  }
  let quads : Array[Quad] = []
  if root.get("@graph") is Some(Array(graph_nodes)) {
    for item in graph_nodes {
      guard item is Object(node) else {
        raise InvalidStructure(detail="'@graph' entries must be JSON objects")
      }
      parse_jsonld_node(node, ctx, graph, quads)
    }
  } else if root.get("@id") is Some(_) {
    parse_jsonld_node(root, ctx, graph, quads)
  } else {
    raise InvalidStructure(
      detail="JSON-LD document must contain '@graph' or '@id'",
    )
  }
  Dataset(quads)
}