///|
let max_dictionary_files_per_graph : Int32 = 64

///|
/// Raised when creating or merging a local SKOS concept fails validation or parsing.
#derive(Eq, Debug)
pub(all) suberror DictionaryConceptError {
  EmptyLabel
  EmptyDefinition
  ExistingTurtleInvalid(String)
}

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

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

///|
/// Human-readable message for a `DictionaryConceptError`.
pub fn DictionaryConceptError::message(self : DictionaryConceptError) -> String {
  match self {
    EmptyLabel => "A concept preferred label must not be empty."
    EmptyDefinition => "A concept definition must not be empty."
    ExistingTurtleInvalid(detail) =>
      "Existing local dictionary Turtle could not be parsed: \{detail}"
  }
}

///|
fn local_dictionary_prefixes() -> Array[(String, @rdf.Iri)] {
  let base = @rdf.standard_prefixes()
  match
    (Some(@rdf.Iri("https://mission-control.local/dict/")) catch { _ => None }) {
    Some(local_iri) => base.push(("local", local_iri))
    None => ()
  }
  base
}

///|
/// Validates a new local SKOS concept, merges it into `existing_ttl` (if any),
/// and returns the updated canonical Turtle serialization.
pub fn merge_local_concept_turtle(
  existing_ttl : String,
  pref_label~ : String,
  definition~ : String,
  alt_labels~ : ReadOnlyArray[String] = [],
) -> String raise DictionaryConceptError {
  let clean_label = pref_label.trim().to_owned()
  guard !clean_label.is_empty() else { raise EmptyLabel }
  let clean_def = definition.trim().to_owned()
  guard !clean_def.is_empty() else { raise EmptyDefinition }
  let existing : @rdf.Dataset = if existing_ttl.trim().is_empty() {
    @rdf.Dataset::empty()
  } else {
    @rdf.parse_turtle(existing_ttl) catch {
      err => raise ExistingTurtleInvalid(@debug.to_string(err))
    }
  }
  let existing_concepts = @rdf.extract_skos_concepts(existing)
  let existing_iri_for_label : @rdf.Iri? = existing_concepts
    .iter()
    .find_first(c => c.pref_label() == clean_label)
    .map(c => c.iri())
  let concept_iri : @rdf.Iri = match existing_iri_for_label {
    Some(iri) => iri
    None => {
      let occupied : Map[String, Bool] = Map([])
      for q in existing.quads() {
        match q.subject() {
          IriSubject(iri) => occupied[iri.as_str()] = true
          BlankSubject(_) => ()
        }
      }
      let base_slug = slug_of(clean_label, "concept")
      let mut candidate_slug = base_slug
      let mut suffix = 2
      while occupied.contains(
              "https://mission-control.local/dict/\{candidate_slug}",
            ) {
        candidate_slug = "\{base_slug}-\{suffix}"
        suffix += 1
      }
      @rdf.Iri("https://mission-control.local/dict/\{candidate_slug}") catch {
        _ =>
          @rdf.Iri("https://mission-control.local/dict/concept") catch {
            _ => abort("fallback concept IRI is valid")
          }
      }
    }
  }
  let clean_alts : Array[String] = []
  for raw in alt_labels {
    let trimmed = raw.trim().to_owned()
    if !trimmed.is_empty() {
      clean_alts.push(trimmed)
    }
  }
  let concept = @rdf.SkosConcept(
    iri=concept_iri,
    pref_label=clean_label,
    definition=clean_def,
    alt_labels=clean_alts,
  )
  let new_quads = @rdf.concept_to_quads(concept)
  let subject = @rdf.Subject::IriSubject(concept_iri)
  let kept : Array[@rdf.Quad] = []
  for q in existing.quads() {
    if q.subject() != subject {
      kept.push(q)
    }
  }
  for q in new_quads {
    kept.push(q)
  }
  let merged = @rdf.Dataset(kept)
  let triples = merged.triples_in(DefaultGraph)
  @rdf.serialize_turtle(triples, prefixes=local_dictionary_prefixes())
}

///|
fn render_concept_wire(
  concept : @rdf.SkosConcept,
  graph_id~ : String,
  graph_name~ : String,
  access~ : @app.SourceAccess,
) -> @app.WireDictionaryConcept {
  let quads = @rdf.concept_to_quads(concept)
  let triples : Array[@rdf.Triple] = quads.iter().map(q => q.triple()).collect()
  let ro_triples = ReadOnlyArray::from_array(triples)
  let prefixes = local_dictionary_prefixes()
  let turtle = @rdf.serialize_turtle(ro_triples, prefixes~)
  let jsonld = @rdf.serialize_jsonld(ro_triples, prefixes~)
  {
    iri: concept.iri().as_str(),
    graph_id,
    graph_name,
    access,
    pref_label: concept.pref_label(),
    definition: concept.definition(),
    alt_labels: concept.alt_labels(),
    deprecated: concept.deprecated(),
    broader: ReadOnlyArray::from_array(
      concept.broader().iter().map(i => i.as_str()).collect(),
    ),
    narrower: ReadOnlyArray::from_array(
      concept.narrower().iter().map(i => i.as_str()).collect(),
    ),
    related: ReadOnlyArray::from_array(
      concept.related().iter().map(i => i.as_str()).collect(),
    ),
    constraints: ReadOnlyArray::from_array(
      concept.constraints().iter().map(c => c.summary()).collect(),
    ),
    turtle,
    jsonld,
  }
}

///|
fn ascii_lower(text : String) -> String {
  let buf = StringBuilder()
  for c in text {
    if c is ('A'..<='Z') {
      buf.write_char((c.to_int() + 32).unsafe_to_char())
    } else {
      buf.write_char(c)
    }
  }
  buf.to_string()
}

///|
/// Runs deterministic Prose Term Audit over live workspace intent documents
/// against all loaded Data Dictionary concepts.
pub fn audit_intent_prose(
  concepts : ReadOnlyArray[@app.WireDictionaryConcept],
  intent : @app.WorkspaceIntent,
) -> ReadOnlyArray[@app.WireTermAuditFinding] {
  let by_iri : Map[String, @app.WireDictionaryConcept] = Map([])
  for c in concepts {
    by_iri[c.iri] = c
  }
  let findings : Array[@app.WireTermAuditFinding] = []
  let seen : Map[String, Bool] = Map([])
  let mut seq = 1
  for item in intent.items {
    for doc in item.packet.documents {
      for line in doc.source_lines {
        let trimmed = line.trim().to_owned()
        if trimmed.is_empty() {
          continue
        }
        let lower_line = ascii_lower(trimmed)
        for c in concepts {
          if c.deprecated {
            let terms : Array[String] = [c.pref_label]
            for alt in c.alt_labels {
              terms.push(alt)
            }
            for term in terms {
              let clean_term = term.trim().to_owned()
              if clean_term.length() < 2 {
                continue
              }
              if lower_line.contains(ascii_lower(clean_term)) {
                let dedup = "\{doc.path}::\{clean_term}"
                if !seen.contains(dedup) {
                  seen[dedup] = true
                  let (suggested_label, suggested_iri) = match
                    c.related.get(0).bind(iri => by_iri.get(iri)) {
                    Some(target) => (target.pref_label, target.iri)
                    None => (c.pref_label, c.iri)
                  }
                  findings.push({
                    id: "audit-\{seq}",
                    kind: "deprecated_synonym",
                    term: clean_term,
                    suggested_label,
                    suggested_iri,
                    document_path: doc.path,
                    excerpt: truncate_chars(trimmed, 160),
                  })
                  seq += 1
                }
              }
            }
          } else {
            let pref_lower = ascii_lower(c.pref_label)
            for alt in c.alt_labels {
              let clean_alt = alt.trim().to_owned()
              if clean_alt.length() < 2 {
                continue
              }
              let alt_lower = ascii_lower(clean_alt)
              if lower_line.contains(alt_lower) &&
                !lower_line.contains(pref_lower) {
                let dedup = "\{doc.path}::\{clean_alt}"
                if !seen.contains(dedup) {
                  seen[dedup] = true
                  findings.push({
                    id: "audit-\{seq}",
                    kind: "synonym_normalization",
                    term: clean_alt,
                    suggested_label: c.pref_label,
                    suggested_iri: c.iri,
                    document_path: doc.path,
                    excerpt: truncate_chars(trimmed, 160),
                  })
                  seq += 1
                }
              }
            }
          }
        }
      }
    }
  }
  ReadOnlyArray::from_array(findings)
}

///|
priv struct DictGraphSpec {
  id : String
  name : String
  access : @app.SourceAccess
  origin_path : String
  folder : FolderPath
  confine_to_root : FolderPath?
}

///|
fn read_graph_files(
  spec : DictGraphSpec,
  entries : Array[String],
  idx : Int32,
  dataset : @rdf.Dataset,
  problems : Array[String],
) -> Inquiry[@rdf.Dataset] {
  if idx >= entries.length() {
    return Done(dataset)
  }
  let name = entries[idx]
  let is_ttl = name.has_suffix(".ttl")
  let is_jsonld = name.has_suffix(".jsonld")
  if !is_ttl && !is_jsonld {
    return read_graph_files(spec, entries, idx + 1, dataset, problems)
  }
  let file_path = spec.folder.join([name])
  let read_and_merge = () => {
    ReadFile(file_path, text => {
      let next_ds = match text {
        Found(content) => {
          let graph_name : @rdf.GraphName = match
            (Some(@rdf.Iri(spec.id)) catch { _ => None }) {
            Some(iri) => NamedGraph(iri)
            None => DefaultGraph
          }
          if is_ttl {
            let parsed : @rdf.Dataset? = Some(
              @rdf.parse_turtle(content, graph=graph_name),
            ) catch {
              err => {
                problems.push(
                  "\{spec.name}/\{name}: Turtle parse error: \{@debug.to_string(err)}",
                )
                None
              }
            }
            match parsed {
              Some(ds) => dataset.merge(ds)
              None => dataset
            }
          } else {
            let parsed : @rdf.Dataset? = Some(
              @rdf.parse_jsonld(content, graph=graph_name),
            ) catch {
              err => {
                problems.push(
                  "\{spec.name}/\{name}: JSON-LD parse error: \{@debug.to_string(err)}",
                )
                None
              }
            }
            match parsed {
              Some(ds) => dataset.merge(ds)
              None => dataset
            }
          }
        }
        TooLarge => {
          problems.push("\{spec.name}/\{name}: skipped (exceeds 1 MiB)")
          dataset
        }
        TimedOut => {
          problems.push("\{spec.name}/\{name}: timed out reading file")
          dataset
        }
        Failed(reason) => {
          problems.push("\{spec.name}/\{name}: \{reason}")
          dataset
        }
        Missing => dataset
      }
      read_graph_files(spec, entries, idx + 1, next_ds, problems)
    })
  }
  match spec.confine_to_root {
    Some(real_root) =>
      RealPath(file_path, real_ans => {
        match real_ans {
          Resolved(real_file) =>
            if real_root.contains(real_file) {
              read_and_merge()
            } else {
              problems.push(
                "\{spec.name}/\{name}: skipped symlink escaping workspace root",
              )
              read_graph_files(spec, entries, idx + 1, dataset, problems)
            }
          Missing => read_graph_files(spec, entries, idx + 1, dataset, problems)
          TimedOut => {
            problems.push(
              "\{spec.name}/\{name}: timed out verifying canonical path",
            )
            read_graph_files(spec, entries, idx + 1, dataset, problems)
          }
          Failed(reason) => {
            problems.push(
              "\{spec.name}/\{name}: failed verifying canonical path (\{reason})",
            )
            read_graph_files(spec, entries, idx + 1, dataset, problems)
          }
        }
      })
    None => read_and_merge()
  }
}

///|
fn truncate_chars(text : String, max_chars : Int32) -> String {
  let chars = text.iter().collect()
  if chars.length() <= max_chars {
    return text
  }
  let keep = if max_chars > 3 { max_chars - 3 } else { max_chars }
  let buf = StringBuilder()
  for i in 0.. 3 {
    buf.write_string("...")
  }
  buf.to_string()
}

///|
fn load_graph_specs(
  specs : Array[DictGraphSpec],
  idx : Int32,
  graphs_acc : Array[@app.WireDictionaryGraph],
  concepts_acc : Array[@app.WireDictionaryConcept],
  problems : Array[String],
) -> Inquiry[Unit] {
  if idx >= specs.length() {
    return Done(())
  }
  let spec = specs[idx]
  let read_dir = () => {
    Names(spec.folder, listing => {
      match listing {
        Entries(raw_entries) => {
          let filtered : Array[String] = []
          for entry in raw_entries {
            if !entry.has_prefix(".") &&
              (entry.has_suffix(".ttl") || entry.has_suffix(".jsonld")) {
              filtered.push(entry)
            }
          }
          filtered.sort_by((a, b) => a.lexical_compare(b))
          let capped : Array[String] = []
          for entry in filtered {
            if capped.length() < max_dictionary_files_per_graph {
              capped.push(entry)
            }
          }
          read_graph_files(spec, capped, 0, @rdf.Dataset::empty(), problems).then(ds => {
              let skos_list = @rdf.extract_skos_concepts(ds)
              for c in skos_list {
                concepts_acc.push(
                  render_concept_wire(
                    c,
                    graph_id=spec.id,
                    graph_name=spec.name,
                    access=spec.access,
                  ),
                )
              }
              graphs_acc.push({
                id: spec.id,
                name: spec.name,
                access: spec.access,
                origin_path: spec.origin_path,
                concept_count: skos_list.length(),
              })
              load_graph_specs(
                specs,
                idx + 1,
                graphs_acc,
                concepts_acc,
                problems,
              )
            },
          )
        }
        Missing | Failed(_) =>
          load_graph_specs(specs, idx + 1, graphs_acc, concepts_acc, problems)
      }
    })
  }
  match spec.confine_to_root {
    Some(real_root) =>
      RealPath(spec.folder, dir_ans => {
        match dir_ans {
          Resolved(real_dir) =>
            if real_root.contains(real_dir) {
              read_dir()
            } else {
              problems.push(
                "\{spec.name}: skipped dictionary folder escaping workspace root",
              )
              load_graph_specs(
                specs,
                idx + 1,
                graphs_acc,
                concepts_acc,
                problems,
              )
            }
          Missing =>
            load_graph_specs(specs, idx + 1, graphs_acc, concepts_acc, problems)
          TimedOut => {
            problems.push(
              "\{spec.name}: timed out verifying canonical dictionary folder path",
            )
            load_graph_specs(specs, idx + 1, graphs_acc, concepts_acc, problems)
          }
          Failed(reason) => {
            problems.push(
              "\{spec.name}: failed verifying canonical dictionary folder path (\{reason})",
            )
            load_graph_specs(specs, idx + 1, graphs_acc, concepts_acc, problems)
          }
        }
      })
    None => read_dir()
  }
}

///|
/// Pure `Inquiry` loading all available local (`.mission-control/dictionary`)
/// and mounted (`role = "dictionary"`) RDF/SKOS graphs for a workspace and
/// running live Prose Term Audit against `intent`.
pub fn inspect_workspace_dictionary(
  workspace_id : @app.WorkspaceId,
  workspace_root : FolderPath,
  sources : DomainWorkspaceSources,
  intent : @app.WorkspaceIntent,
) -> Inquiry[@app.WorkspaceDictionary] {
  RealPath(workspace_root, root_ans => {
    let problems : Array[String] = []
    let real_root_opt : FolderPath? = match root_ans {
      Resolved(real_root) => Some(real_root)
      Missing => {
        problems.push(
          "Workspace root missing while verifying dictionary confinement.",
        )
        None
      }
      TimedOut => {
        problems.push(
          "Timed out resolving workspace root for dictionary confinement.",
        )
        None
      }
      Failed(reason) => {
        problems.push(
          "Failed resolving workspace root for dictionary confinement: \{reason}",
        )
        None
      }
    }
    let specs : Array[DictGraphSpec] = []
    for src in sources.sources {
      match src {
        InTree(in_tree) if in_tree.role is Dictionary &&
          in_tree.status is Available =>
          match real_root_opt {
            Some(real_root) =>
              specs.push({
                id: "urn:mc:dict:local",
                name: "Local Dictionary",
                access: ReadWrite,
                origin_path: in_tree.location.key(),
                folder: in_tree.path,
                confine_to_root: Some(real_root),
              })
            None =>
              problems.push(
                "Local Dictionary: skipped because workspace root canonical path could not be verified.",
              )
          }
        Mounted(Resolved(mount)) if mount.role is Dictionary &&
          mount.status is Available =>
          specs.push({
            id: "urn:mc:dict:mount:\{mount.name.to_string()}",
            name: mount.name.to_string(),
            access: mount.access,
            origin_path: mount.target.display(),
            folder: mount.resolved_root,
            confine_to_root: None,
          })
        _ => ()
      }
    }
    let graphs_acc : Array[@app.WireDictionaryGraph] = []
    let concepts_acc : Array[@app.WireDictionaryConcept] = []
    load_graph_specs(specs, 0, graphs_acc, concepts_acc, problems).map(_ => {
      concepts_acc.sort_by((a, b) => a.pref_label.lexical_compare(b.pref_label))
      let ro_concepts = ReadOnlyArray::from_array(concepts_acc)
      let findings = audit_intent_prose(ro_concepts, intent)
      {
        workspace: workspace_id,
        graphs: ReadOnlyArray::from_array(graphs_acc),
        concepts: ro_concepts,
        findings,
        problems: ReadOnlyArray::from_array(problems),
      }
    })
  })
}