// Validated RDF 1.1 terms, triples, quads, and standard vocabulary IRIs.

///|
/// Reason why an `Iri` failed RFC 3987 / RDF 1.1 validation.
#derive(Eq, Debug)
pub(all) enum IriRule {
  Empty
  MissingScheme
  InvalidScheme
  IllegalCharacter
}

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

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

///|
/// Parse error for `Iri`.
#derive(Eq, Debug)
pub suberror IriError {
  InvalidIri(input~ : String, rule~ : IriRule)
}

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

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

///|
/// Validated absolute IRI (`scheme:rest` with no whitespace, control chars, or
/// forbidden RDF delimiter characters).
#derive(Eq, Compare, Hash, Debug)
pub struct Iri {
  priv value : String
}

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

///|
pub extend Iri with Compare::{compare}

///|
pub extend Iri with Hash::{hash_combine}

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

///|
fn is_ascii_letter(ch : Char) -> Bool {
  (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
}

///|
fn is_scheme_char(ch : Char) -> Bool {
  is_ascii_letter(ch) ||
  (ch >= '0' && ch <= '9') ||
  ch == '+' ||
  ch == '-' ||
  ch == '.'
}

///|
/// Parses a validated absolute IRI.
pub fn Iri::Iri(raw : String) -> Iri raise IriError {
  if raw.is_empty() {
    raise InvalidIri(input=raw, rule=Empty)
  }
  guard raw.find(":") is Some(colon) else {
    raise InvalidIri(input=raw, rule=MissingScheme)
  }
  if colon == 0 {
    raise InvalidIri(input=raw, rule=InvalidScheme)
  }
  let scheme = raw[:colon].to_owned()
  let mut idx = 0
  for ch in scheme {
    if idx == 0 && !is_ascii_letter(ch) {
      raise InvalidIri(input=raw, rule=InvalidScheme)
    }
    if !is_scheme_char(ch) {
      raise InvalidIri(input=raw, rule=InvalidScheme)
    }
    idx += 1
  }
  for ch in raw {
    let cp = ch.to_int()
    if cp <= 0x20 ||
      cp == 0x7F ||
      ch == '<' ||
      ch == '>' ||
      ch == '"' ||
      ch == '{' ||
      ch == '}' ||
      ch == '|' ||
      ch == '^' ||
      ch == '`' ||
      ch == '\\' {
      raise InvalidIri(input=raw, rule=IllegalCharacter)
    }
  }
  { value: raw, }
}

///|
/// Returns the IRI text.
pub fn Iri::as_str(self : Iri) -> String {
  self.value
}

///|
pub impl Show for Iri with fn output(self, logger) {
  logger.write_string(self.value)
}

///|
/// Standard `rdf:type` IRI.
pub fn Iri::rdf_type() -> Iri {
  { value: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", }
}

///|
/// Standard `xsd:string` IRI.
pub fn Iri::xsd_string() -> Iri {
  { value: "http://www.w3.org/2001/XMLSchema#string", }
}

///|
/// Standard `xsd:boolean` IRI.
pub fn Iri::xsd_boolean() -> Iri {
  { value: "http://www.w3.org/2001/XMLSchema#boolean", }
}

///|
/// Standard `xsd:integer` IRI.
pub fn Iri::xsd_integer() -> Iri {
  { value: "http://www.w3.org/2001/XMLSchema#integer", }
}

///|
/// Standard `skos:Concept` IRI.
pub fn Iri::skos_concept() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#Concept", }
}

///|
/// Standard `skos:prefLabel` IRI.
pub fn Iri::skos_pref_label() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#prefLabel", }
}

///|
/// Standard `skos:altLabel` IRI.
pub fn Iri::skos_alt_label() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#altLabel", }
}

///|
/// Standard `skos:hiddenLabel` IRI.
pub fn Iri::skos_hidden_label() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#hiddenLabel", }
}

///|
/// Standard `skos:definition` IRI.
pub fn Iri::skos_definition() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#definition", }
}

///|
/// Standard `skos:broader` IRI.
pub fn Iri::skos_broader() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#broader", }
}

///|
/// Standard `skos:narrower` IRI.
pub fn Iri::skos_narrower() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#narrower", }
}

///|
/// Standard `skos:related` IRI.
pub fn Iri::skos_related() -> Iri {
  { value: "http://www.w3.org/2004/02/skos/core#related", }
}

///|
/// Standard `owl:deprecated` IRI.
pub fn Iri::owl_deprecated() -> Iri {
  { value: "http://www.w3.org/2002/07/owl#deprecated", }
}

///|
/// Standard `sh:minLength` IRI.
pub fn Iri::sh_min_length() -> Iri {
  { value: "http://www.w3.org/ns/shacl#minLength", }
}

///|
/// Standard `sh:maxLength` IRI.
pub fn Iri::sh_max_length() -> Iri {
  { value: "http://www.w3.org/ns/shacl#maxLength", }
}

///|
/// Standard `sh:pattern` IRI.
pub fn Iri::sh_pattern() -> Iri {
  { value: "http://www.w3.org/ns/shacl#pattern", }
}

///|
/// Standard `sh:datatype` IRI.
pub fn Iri::sh_datatype() -> Iri {
  { value: "http://www.w3.org/ns/shacl#datatype", }
}

///|
/// Standard `sh:message` IRI.
pub fn Iri::sh_message() -> Iri {
  { value: "http://www.w3.org/ns/shacl#message", }
}

///|
/// Standard default namespace prefixes for SKOS, SHACL, OWL, RDF, and XSD.
pub fn standard_prefixes() -> Array[(String, Iri)] {
  [
    ("rdf", { value: "http://www.w3.org/1999/02/22-rdf-syntax-ns#", }),
    ("rdfs", { value: "http://www.w3.org/2000/01/rdf-schema#", }),
    ("xsd", { value: "http://www.w3.org/2001/XMLSchema#", }),
    ("skos", { value: "http://www.w3.org/2004/02/skos/core#", }),
    ("owl", { value: "http://www.w3.org/2002/07/owl#", }),
    ("sh", { value: "http://www.w3.org/ns/shacl#", }),
  ]
}

///|
/// Parse error for `BlankNodeId`.
#derive(Eq, Debug)
pub suberror BlankNodeIdError {
  InvalidBlankNodeId(input~ : String)
}

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

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

///|
/// Validated RDF blank node label (without the leading `_:` prefix).
#derive(Eq, Compare, Hash, Debug)
pub struct BlankNodeId {
  priv label : String
}

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

///|
pub extend BlankNodeId with Compare::{compare}

///|
pub extend BlankNodeId with Hash::{hash_combine}

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

///|
/// Parses a validated blank node label (`[A-Za-z0-9_.-]+`, not starting or
/// ending with `.`).
pub fn BlankNodeId::BlankNodeId(
  raw : String,
) -> BlankNodeId raise BlankNodeIdError {
  if raw.is_empty() || raw.has_prefix(".") || raw.has_suffix(".") {
    raise InvalidBlankNodeId(input=raw)
  }
  for ch in raw {
    let ok = is_ascii_letter(ch) ||
      (ch >= '0' && ch <= '9') ||
      ch == '_' ||
      ch == '-' ||
      ch == '.'
    if !ok {
      raise InvalidBlankNodeId(input=raw)
    }
  }
  { label: raw, }
}

///|
/// Returns the blank node label without `_:`.
pub fn BlankNodeId::as_str(self : BlankNodeId) -> String {
  self.label
}

///|
pub impl Show for BlankNodeId with fn output(self, logger) {
  logger.write_string("_:\{self.label}")
}

///|
/// Parse error for `LangTag`.
#derive(Eq, Debug)
pub suberror LangTagError {
  InvalidLangTag(input~ : String)
}

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

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

///|
/// Validated lowercase BCP-47 language tag (for example `"en"` or `"en-us"`).
#derive(Eq, Compare, Hash, Debug)
pub struct LangTag {
  priv tag : String
}

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

///|
pub extend LangTag with Compare::{compare}

///|
pub extend LangTag with Hash::{hash_combine}

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

///|
/// Parses and lowercases a BCP-47 language tag.
pub fn LangTag::LangTag(raw : String) -> LangTag raise LangTagError {
  if raw.is_empty() {
    raise InvalidLangTag(input=raw)
  }
  let parts : Array[String] = []
  let mut idx = 0
  for part_view in raw.split("-") {
    let part = part_view.to_owned()
    if part.is_empty() || part.length() > 8 {
      raise InvalidLangTag(input=raw)
    }
    let buf = StringBuilder()
    for ch in part {
      if idx == 0 {
        if !is_ascii_letter(ch) {
          raise InvalidLangTag(input=raw)
        }
      } else if !is_ascii_letter(ch) && !(ch >= '0' && ch <= '9') {
        raise InvalidLangTag(input=raw)
      }
      let lowered = if ch >= 'A' && ch <= 'Z' {
        (ch.to_int() + 32).unsafe_to_char()
      } else {
        ch
      }
      buf.write_char(lowered)
    }
    parts.push(buf.to_string())
    idx += 1
  }
  { tag: parts.join("-"), }
}

///|
/// Canonical English language tag (`"en"`).
pub fn LangTag::en() -> LangTag {
  { tag: "en", }
}

///|
/// Returns the normalized lowercase language tag.
pub fn LangTag::as_str(self : LangTag) -> String {
  self.tag
}

///|
pub impl Show for LangTag with fn output(self, logger) {
  logger.write_string(self.tag)
}

///|
/// An RDF 1.1 literal value.
#derive(Eq, Compare, Hash, Debug)
pub(all) enum Literal {
  Plain(String)
  LangString(value~ : String, lang~ : LangTag)
  Typed(value~ : String, datatype~ : Iri)
}

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

///|
pub extend Literal with Compare::{compare}

///|
pub extend Literal with Hash::{hash_combine}

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

///|
/// Extracts the lexical string of any literal variant.
pub fn Literal::lexical(self : Literal) -> String {
  match self {
    Plain(v) => v
    LangString(value~, ..) => value
    Typed(value~, ..) => value
  }
}

///|
/// RDF triple subject (`Iri` or `BlankNodeId`).
#derive(Eq, Compare, Hash, Debug)
pub(all) enum Subject {
  IriSubject(Iri)
  BlankSubject(BlankNodeId)
}

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

///|
pub extend Subject with Compare::{compare}

///|
pub extend Subject with Hash::{hash_combine}

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

///|
/// RDF triple object (`Iri`, `BlankNodeId`, or `Literal`).
#derive(Eq, Compare, Hash, Debug)
pub(all) enum ObjectTerm {
  IriObject(Iri)
  BlankObject(BlankNodeId)
  LiteralObject(Literal)
}

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

///|
pub extend ObjectTerm with Compare::{compare}

///|
pub extend ObjectTerm with Hash::{hash_combine}

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

///|
/// Target graph inside an RDF dataset (`DefaultGraph` or `NamedGraph(Iri)`).
#derive(Eq, Compare, Hash, Debug)
pub(all) enum GraphName {
  DefaultGraph
  NamedGraph(Iri)
}

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

///|
pub extend GraphName with Compare::{compare}

///|
pub extend GraphName with Hash::{hash_combine}

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

///|
/// An RDF 1.1 triple `(subject, predicate, object)`.
#derive(Eq, Compare, Hash, Debug)
pub struct Triple {
  priv subject : Subject
  priv predicate : Iri
  priv object : ObjectTerm
}

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

///|
pub extend Triple with Compare::{compare}

///|
pub extend Triple with Hash::{hash_combine}

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

///|
/// Constructs an immutable `Triple`.
pub fn Triple::Triple(
  subject~ : Subject,
  predicate~ : Iri,
  object~ : ObjectTerm,
) -> Triple {
  { subject, predicate, object, }
}

///|
/// Triple subject.
pub fn Triple::subject(self : Triple) -> Subject {
  self.subject
}

///|
/// Triple predicate IRI.
pub fn Triple::predicate(self : Triple) -> Iri {
  self.predicate
}

///|
/// Triple object term.
pub fn Triple::object(self : Triple) -> ObjectTerm {
  self.object
}

///|
/// An RDF 1.1 quad `(graph, subject, predicate, object)`.
#derive(Eq, Compare, Hash, Debug)
pub struct Quad {
  priv graph : GraphName
  priv triple : Triple
}

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

///|
pub extend Quad with Compare::{compare}

///|
pub extend Quad with Hash::{hash_combine}

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

///|
/// Constructs an immutable `Quad`.
pub fn Quad::Quad(
  graph~ : GraphName = DefaultGraph,
  subject~ : Subject,
  predicate~ : Iri,
  object~ : ObjectTerm,
) -> Quad {
  { graph, triple: Triple(subject~, predicate~, object~), }
}

///|
/// Owning graph name.
pub fn Quad::graph(self : Quad) -> GraphName {
  self.graph
}

///|
/// Underlying triple.
pub fn Quad::triple(self : Quad) -> Triple {
  self.triple
}

///|
/// Quad subject.
pub fn Quad::subject(self : Quad) -> Subject {
  self.triple.subject
}

///|
/// Quad predicate.
pub fn Quad::predicate(self : Quad) -> Iri {
  self.triple.predicate
}

///|
/// Quad object.
pub fn Quad::object(self : Quad) -> ObjectTerm {
  self.triple.object
}