///|
/// A canonical monomial. Repeated factors represent repeated uses of a record.
#derive(Eq, ToJson)
pub(all) struct Term {
  coefficient : Int32
  factors : Array[String]
}

///|
/// Nonnegative integer polynomial. Construct through token/constant/add/multiply.
#derive(Eq, ToJson)
pub(all) struct Polynomial {
  terms : Array[Term]
}

///|
/// A bounded implementation: at most 4096 terms, degree 64, coefficient 10^9.
fn canonical(terms : Array[Term]) -> Result[Polynomial, String] {
  if terms.length() > 65536 {
    return Err("term work limit")
  }
  let out : Array[Term] = []
  for term in terms {
    if term.coefficient < 0 || term.coefficient > 1000000000 {
      return Err("coefficient outside 0..1000000000")
    }
    if term.factors.length() > 64 {
      return Err("degree limit 64")
    }
    if term.coefficient == 0 {
      continue
    }
    let factors = term.factors.copy()
    for factor in factors {
      if factor == "" {
        return Err("empty token")
      }
    }
    factors.sort_by((a, b) => a.lexical_compare(b))
    let mut found = false
    for i = 0; i < out.length(); i = i + 1 {
      if out[i].factors == factors {
        if out[i].coefficient > 1000000000 - term.coefficient {
          return Err("coefficient overflow")
        }
        out[i] = {
          coefficient: out[i].coefficient + term.coefficient,
          factors,
        }
        found = true
        break
      }
    }
    if !found {
      if out.length() >= 4096 {
        return Err("term limit 4096")
      }
      out.push({ coefficient: term.coefficient, factors, })
    }
  }
  out.sort_by((a, b) => compare_factors(a.factors, b.factors))
  Ok({ terms: out, })
}

///|
fn compare_factors(a : Array[String], b : Array[String]) -> Int32 {
  for i = 0; i < a.length() && i < b.length(); i = i + 1 {
    let c = a[i].lexical_compare(b[i])
    if c != 0 {
      return c
    }
  }
  a.length().compare(b.length())
}

///|
pub fn polynomial(terms : Array[Term]) -> Result[Polynomial, String] {
  canonical(terms)
}

///|
pub fn token(name : String) -> Result[Polynomial, String] {
  canonical([{ coefficient: 1, factors: [name], }])
}

///|
pub fn constant(value : Int32) -> Result[Polynomial, String] {
  canonical([{ coefficient: value, factors: [], }])
}

///|
pub fn add(a : Polynomial, b : Polynomial) -> Result[Polynomial, String] {
  let terms = a.terms.copy()
  for t in b.terms {
    terms.push(t)
  }
  canonical(terms)
}

///|
pub fn multiply(a : Polynomial, b : Polynomial) -> Result[Polynomial, String] {
  let a = match canonical(a.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let b = match canonical(b.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  if a.terms.length() * b.terms.length() > 65536 {
    return Err("product work limit 65536")
  }
  let terms : Array[Term] = []
  for x in a.terms {
    for y in b.terms {
      if x.coefficient > 1000000000 / y.coefficient {
        return Err("coefficient overflow")
      }
      let factors = x.factors.copy()
      for f in y.factors {
        factors.push(f)
      }
      terms.push({ coefficient: x.coefficient * y.coefficient, factors, })
    }
  }
  canonical(terms)
}

///|
/// Semiring homomorphism into nonnegative real numbers (NOT event probability).
pub fn evaluate(
  p : Polynomial,
  weights : Map[String, Double],
) -> Result[Double, String] {
  let p = match canonical(p.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let mut sum = 0.0
  for t in p.terms {
    let mut value = t.coefficient.to_double()
    for f in t.factors {
      let w = match weights.get(f) {
        Some(w) => w
        None => return Err("missing token: " + f)
      }
      if w.is_nan() || w < 0.0 || w > 1.0e100 {
        return Err("invalid nonnegative weight")
      }
      value = value * w
      if value > 1.0e300 {
        return Err("evaluation overflow")
      }
    }
    sum = sum + value
    if sum > 1.0e300 {
      return Err("evaluation overflow")
    }
  }
  Ok(sum)
}

///|
/// Formal derivative; x*x differentiates to 2*x, preserving repeated use.
pub fn derivative(p : Polynomial, name : String) -> Result[Polynomial, String] {
  let p = match canonical(p.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let terms : Array[Term] = []
  for t in p.terms {
    let mut count = 0
    let factors : Array[String] = []
    for f in t.factors {
      if f == name {
        count = count + 1
      }
      if f != name || count != 1 {
        factors.push(f)
      }
    }
    if count > 0 {
      if t.coefficient > 1000000000 / count {
        return Err("derivative coefficient overflow")
      }
      terms.push({ coefficient: t.coefficient * count, factors, })
    }
  }
  canonical(terms)
}

///|
/// Boolean deletion semantics: absent tokens disable every monomial using them.
pub fn survives(
  p : Polynomial,
  removed : Array[String],
) -> Result[Bool, String] {
  let p = match canonical(p.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  for t in p.terms {
    let mut alive = true
    for f in t.factors {
      if removed.contains(f) {
        alive = false
        break
      }
    }
    if alive {
      return Ok(true)
    }
  }
  Ok(false)
}

///|
/// Inclusion-minimal sufficient sets of input tokens, not minimum cardinality.
pub fn witnesses(p : Polynomial) -> Result[Array[Array[String]], String] {
  let p = match canonical(p.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let candidates : Array[Array[String]] = []
  for t in p.terms {
    let set : Array[String] = []
    for f in t.factors {
      if !set.contains(f) {
        set.push(f)
      }
    }
    if !candidates.contains(set) {
      candidates.push(set)
    }
  }
  let result : Array[Array[String]] = []
  for a in candidates {
    let mut minimal = true
    for b in candidates {
      if b.length() < a.length() && b.all(x => a.contains(x)) {
        minimal = false
        break
      }
    }
    if minimal {
      result.push(a)
    }
  }
  Ok(result)
}

///| Exact possible-world enumeration for independent tokens, at most 16.

///|
/// Handles overlapping witnesses and repeated factors without double counting.
pub fn probability(
  p : Polynomial,
  probabilities : Map[String, Double],
) -> Result[Double, String] {
  let p = match canonical(p.terms) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let names : Array[String] = []
  for t in p.terms {
    for f in t.factors {
      if !names.contains(f) {
        names.push(f)
      }
    }
  }
  if names.length() > 16 {
    return Err("possible-world token limit 16")
  }
  let ps : Array[Double] = []
  for name in names {
    let v = match probabilities.get(name) {
      Some(v) => v
      None => return Err("missing token: " + name)
    }
    if v.is_nan() || v < 0.0 || v > 1.0 {
      return Err("probability outside [0,1]")
    }
    ps.push(v)
  }
  let mut answer = 0.0
  let masks : Array[Int32] = []
  for term in p.terms {
    let mut mask = 0
    for f in term.factors {
      match names.search(f) {
        Some(i) => mask = mask | (1 << i)
        None => ()
      }
    }
    masks.push(mask)
  }
  if masks.length() * (1 << names.length()) > 10000000 {
    return Err("possible-world work limit 10000000")
  }
  for world = 0; world < 1 << names.length(); world = world + 1 {
    let mut mass = 1.0
    for i = 0; i < names.length(); i = i + 1 {
      if (world & (1 << i)) == 0 {
        mass = mass * (1.0 - ps[i])
      } else {
        mass = mass * ps[i]
      }
    }
    if masks.any(mask => (world & mask) == mask) {
      answer = answer + mass
    }
  }
  Ok(answer)
}