///|
/// Where the sanctioned computation of an Attested Computation lives
/// (OKF v0.3, section 10.3).
#derive(Eq, Debug)
pub(all) enum ComputationSource {
  /// A file in the bundle named by the `computation` path field.
  File(BundlePath)
  /// The first fenced code block in the `Computation` body section.
  Inline(CodeBlock)
}

///|
/// A reason why a concept cannot be treated as attestable (OKF v0.3,
/// sections 10.2 and 10.3).
#derive(Eq, Debug)
pub(all) enum AttestabilityProblem {
  /// The concept does not have `type: Attested Computation`.
  NotAnAttestedComputation
  /// The `runtime` field is missing or blank.
  MissingRuntime
  /// The `attester.resource` field is missing or blank.
  MissingAttester
  /// The `attester.resource` path does not resolve to an in-bundle file or URI.
  UnresolvedAttester(String)
  /// Neither `computation` nor a fenced code block in `# Computation` exists.
  MissingComputation
  /// The `computation` path field does not resolve to an in-bundle file.
  UnresolvedComputation(String)
}

///|
/// Whether a concept is attestable and its resolved computation contract
/// (OKF v0.3, sections 10.2, 10.3 and 11.2).
#derive(Eq, Debug)
pub(all) enum Attestability {
  Attestable(
    runtime~ : String,
    source~ : ComputationSource,
    attester~ : String,
    executor~ : Executor?,
    parameters~ : ReadOnlyArray[Parameter],
  )
  NotAttestable(ReadOnlyArray[AttestabilityProblem])
}

///|
pub fn Attestability::is_attestable(self : Attestability) -> Bool {
  self is Attestable(..)
}

///|
let attested_computation_type : ConceptType = { text: "Attested Computation", }

///|
/// True when `doc` is an `Attested Computation` concept.
pub fn Document::is_attested_computation(self : Document) -> Bool {
  self.is_concept() && self.concept_type() == Some(attested_computation_type)
}

///|
/// Fenced code blocks inside the `Computation` section of `doc` (at any ATX
/// heading level, ending at the next heading of the same or higher level).
/// Indented code blocks are excluded (OKF v0.3, section 10.3).
pub fn Document::inline_computation_blocks(self : Document) -> Array[CodeBlock] {
  match self.section("Computation") {
    Some(sec) => sec.code_blocks.iter().filter(c => c.is_fenced).collect()
    None => []
  }
}

///|
fn resolve_bundle_file(
  bundle : Bundle,
  doc : Document,
  value : String,
  resolver : &LinkResolver?,
) -> BundlePath? {
  let res = resolve_field_path_in_bundle(bundle, doc, value, resolver?)
  match res.resolution {
    StoreTarget(path~, escapes=false, ..) =>
      match bundle.bundle_path_of(path) {
        Some(rel) if bundle.document(rel) is Some(_) ||
          bundle.assets().contains(rel) => Some(rel)
        _ => None
      }
    _ => None
  }
}

///|
/// Locates the computation of `doc` per OKF v0.3 section 10.3: the file named
/// by `computation` when present, else the first fenced code block in the
/// `Computation` body section.
pub fn Bundle::locate_computation(
  self : Bundle,
  doc : Document,
  resolver? : &LinkResolver,
) -> ComputationSource? {
  match doc.metadata().computation() {
    Some(path_text) =>
      resolve_bundle_file(self, doc, path_text, resolver).map(p => File(p))
    None =>
      match doc.inline_computation_blocks() {
        [first, ..] => Some(Inline(first))
        [] => None
      }
  }
}

///|
/// Evaluates whether `doc` is attestable under OKF v0.3 sections 10.2, 10.3
/// and 11.2. Consumers MUST NOT show a value as attested unless this returns
/// `Attestable`.
pub fn Bundle::attestability(
  self : Bundle,
  doc : Document,
  resolver? : &LinkResolver,
) -> Attestability {
  if !doc.is_attested_computation() {
    return NotAttestable(ReadOnlyArray::from_array([NotAnAttestedComputation]))
  }
  let meta = doc.metadata()
  let problems : Array[AttestabilityProblem] = []
  let runtime = meta.runtime()
  if runtime is None {
    problems.push(MissingRuntime)
  }
  let attester = meta.attester()
  match attester {
    None => problems.push(MissingAttester)
    Some(att) => {
      let res = resolve_field_path_in_bundle(self, doc, att, resolver?)
      let ok = match res.resolution {
        ExternalUri(_) => true
        StoreTarget(path~, escapes=false, ..) =>
          target_exists_in_bundle(self, path, resolver)
        _ => false
      }
      if !ok {
        problems.push(UnresolvedAttester(att))
      }
    }
  }
  let source = self.locate_computation(doc, resolver?)
  if source is None {
    match meta.computation() {
      Some(path_text) => problems.push(UnresolvedComputation(path_text))
      None => problems.push(MissingComputation)
    }
  }
  if !problems.is_empty() {
    return NotAttestable(ReadOnlyArray::from_array(problems))
  }
  match (runtime, source, attester) {
    (Some(runtime), Some(source), Some(attester)) =>
      Attestable(
        runtime~,
        source~,
        attester~,
        executor=meta.executor(),
        parameters=ReadOnlyArray::from_array(meta.parameters()),
      )
    _ => NotAttestable(ReadOnlyArray::from_array(problems))
  }
}

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

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

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

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

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

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