// Validated domain identifiers, titles, and confined document paths for
// canonical intent models. Pure, zero-I/O, four-target.

///|
/// FNV-1a 32-bit hash over UTF-8 bytes of `text`, formatted as 8 lowercase hex
/// digits. Matches Mission Control's deterministic URN suffix convention.
fn fnv1a32_hex(text : String) -> String {
  let mut hash : UInt32 = 0x811c9dc5U
  for ch in text {
    let cp = ch.to_int().reinterpret_as_uint()
    if cp <= 0x7FU {
      hash = (hash ^ cp) * 0x01000193U
    } else if cp <= 0x7FFU {
      let b0 = 0xC0U | (cp >> 6)
      let b1 = 0x80U | (cp & 0x3FU)
      hash = (hash ^ b0) * 0x01000193U
      hash = (hash ^ b1) * 0x01000193U
    } else if cp <= 0xFFFFU {
      let b0 = 0xE0U | (cp >> 12)
      let b1 = 0x80U | ((cp >> 6) & 0x3FU)
      let b2 = 0x80U | (cp & 0x3FU)
      hash = (hash ^ b0) * 0x01000193U
      hash = (hash ^ b1) * 0x01000193U
      hash = (hash ^ b2) * 0x01000193U
    } else {
      let b0 = 0xF0U | (cp >> 18)
      let b1 = 0x80U | ((cp >> 12) & 0x3FU)
      let b2 = 0x80U | ((cp >> 6) & 0x3FU)
      let b3 = 0x80U | (cp & 0x3FU)
      hash = (hash ^ b0) * 0x01000193U
      hash = (hash ^ b1) * 0x01000193U
      hash = (hash ^ b2) * 0x01000193U
      hash = (hash ^ b3) * 0x01000193U
    }
  }
  let digits = "0123456789abcdef"
  let buf = StringBuilder()
  for shift in [28, 24, 20, 16, 12, 8, 4, 0] {
    let nibble = ((hash >> shift) & 0xFU).reinterpret_as_int()
    buf.write_char(digits.code_unit_at(nibble).to_int().unsafe_to_char())
  }
  buf.to_string()
}

///|
/// Lowercase ASCII slug derived from arbitrary label text (1..32 chars,
/// falling back to `"item"` when no alphanumeric characters appear).
fn slugify_label(text : String) -> String {
  let buf = StringBuilder()
  let mut last_dash = true
  let mut count = 0
  for ch in text {
    if count >= 32 {
      break
    }
    let lowered = if ch >= 'A' && ch <= 'Z' {
      (ch.to_int() + 32).unsafe_to_char()
    } else {
      ch
    }
    if (lowered >= 'a' && lowered <= 'z') || (lowered >= '0' && lowered <= '9') {
      buf.write_char(lowered)
      last_dash = false
      count += 1
    } else if !last_dash && count > 0 && count < 31 {
      buf.write_char('-')
      last_dash = true
      count += 1
    }
  }
  let raw = buf.to_string().trim_end(chars="-").to_owned()
  if raw.is_empty() {
    "item"
  } else {
    raw
  }
}

///|
fn is_lower_hex(ch : Char) -> Bool {
  (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')
}

///|
fn is_slug_char(ch : Char) -> Bool {
  (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-'
}

///|
/// Reason why a lowercase identifier slug failed validation.
#derive(Eq, Debug)
pub(all) enum SlugRule {
  Empty
  TooLong
  MustStartWithLowerLetter
  InvalidCharacter
  TrailingHyphen
  DoubleHyphen
}

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

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

///|
fn validate_slug(text : String) -> SlugRule? {
  if text.is_empty() {
    return Some(Empty)
  }
  if text.length() > 32 {
    return Some(TooLong)
  }
  let mut idx = 0
  let mut prev_dash = false
  for ch in text {
    if idx == 0 && !(ch >= 'a' && ch <= 'z') {
      return Some(MustStartWithLowerLetter)
    }
    if !is_slug_char(ch) {
      return Some(InvalidCharacter)
    }
    if ch == '-' {
      if prev_dash {
        return Some(DoubleHyphen)
      }
      prev_dash = true
    } else {
      prev_dash = false
    }
    idx += 1
  }
  if prev_dash {
    return Some(TrailingHyphen)
  }
  None
}

///|
/// Parse error for `AdapterId`.
#derive(Eq, Debug)
pub suberror AdapterIdError {
  InvalidAdapterId(input~ : String, rule~ : SlugRule)
}

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

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

///|
/// Validated open identifier for an SDD adapter (for example `"openspec"` or
/// `"bmad"`).
#derive(Eq, Compare, Hash, Debug)
pub struct AdapterId {
  priv value : String
}

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

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

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

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

///|
/// Parses a lowercase ASCII adapter identifier (1..32 chars, starting with a
/// lowercase letter).
pub fn AdapterId::AdapterId(text : String) -> AdapterId raise AdapterIdError {
  match validate_slug(text) {
    Some(rule) => raise InvalidAdapterId(input=text, rule~)
    None => { value: text, }
  }
}

///|
/// Built-in canonical adapter identifier for OpenSpec (`"openspec"`).
pub fn AdapterId::openspec() -> AdapterId {
  { value: "openspec", }
}

///|
/// Returns the underlying string representation.
pub fn AdapterId::as_str(self : AdapterId) -> String {
  self.value
}

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

///|
/// Parse error for `StageId`.
#derive(Eq, Debug)
pub suberror StageIdError {
  InvalidStageId(input~ : String, rule~ : SlugRule)
}

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

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

///|
/// Validated workflow stage identifier (open to custom workspace stages while
/// providing built-in canonical constructors).
#derive(Eq, Compare, Hash, Debug)
pub struct StageId {
  priv value : String
}

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

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

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

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

///|
/// Parses a lowercase ASCII stage identifier (1..32 chars, starting with a
/// lowercase letter).
pub fn StageId::StageId(text : String) -> StageId raise StageIdError {
  match validate_slug(text) {
    Some(rule) => raise InvalidStageId(input=text, rule~)
    None => { value: text, }
  }
}

///|
/// Canonical Explore stage (`"explore"`).
pub fn StageId::explore() -> StageId {
  { value: "explore", }
}

///|
/// Canonical Propose stage (`"propose"`).
pub fn StageId::propose() -> StageId {
  { value: "propose", }
}

///|
/// Canonical Implement stage (`"implement"`).
pub fn StageId::implement() -> StageId {
  { value: "implement", }
}

///|
/// Canonical Verify stage (`"verify"`).
pub fn StageId::verify() -> StageId {
  { value: "verify", }
}

///|
/// Canonical Release stage (`"release"`).
pub fn StageId::release() -> StageId {
  { value: "release", }
}

///|
/// Returns the underlying string representation.
pub fn StageId::as_str(self : StageId) -> String {
  self.value
}

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

///|
/// Reason why an `IntentId` URN failed parsing.
#derive(Eq, Debug)
pub(all) enum IntentIdRule {
  MissingPrefix
  MissingHashSuffix
  InvalidSlug
  InvalidHashHex
}

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

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

///|
/// Parse error for `IntentId`.
#derive(Eq, Debug)
pub suberror IntentIdError {
  InvalidIntentId(input~ : String, rule~ : IntentIdRule)
}

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

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

///|
/// Deterministic workspace-scoped RFC 8141 URN for a canonical intent item
/// (`urn:mc:intent:-`).
#derive(Eq, Compare, Hash, Debug)
pub struct IntentId {
  priv urn : String
}

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

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

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

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

///|
let intent_urn_prefix : String = "urn:mc:intent:"

///|
/// Parses a validated `urn:mc:intent:-<8-hex>` identifier.
pub fn IntentId::IntentId(text : String) -> IntentId raise IntentIdError {
  guard text.has_prefix(intent_urn_prefix) else {
    raise InvalidIntentId(input=text, rule=MissingPrefix)
  }
  let rest = text[intent_urn_prefix.length():].to_owned()
  guard rest.length() >= 10 else {
    raise InvalidIntentId(input=text, rule=MissingHashSuffix)
  }
  let split_at = rest.length() - 9
  guard rest.code_unit_at(split_at) == '-' else {
    raise InvalidIntentId(input=text, rule=MissingHashSuffix)
  }
  let slug = rest[:split_at].to_owned()
  let hex = rest[split_at + 1:].to_owned()
  if slug.is_empty() ||
    slug.length() > 32 ||
    slug.has_prefix("-") ||
    slug.has_suffix("-") {
    raise InvalidIntentId(input=text, rule=InvalidSlug)
  }
  for ch in slug {
    if !is_slug_char(ch) {
      raise InvalidIntentId(input=text, rule=InvalidSlug)
    }
  }
  if hex.length() != 8 {
    raise InvalidIntentId(input=text, rule=InvalidHashHex)
  }
  for ch in hex {
    if !is_lower_hex(ch) {
      raise InvalidIntentId(input=text, rule=InvalidHashHex)
    }
  }
  { urn: text, }
}

///|
/// Derives a deterministic `IntentId` scoped to `workspace_urn`, `adapter`, and
/// `origin_key`.
pub fn IntentId::for_origin(
  workspace_urn~ : String,
  adapter~ : AdapterId,
  label~ : String,
  origin_key~ : String,
) -> IntentId {
  let slug = slugify_label(label)
  let digest = fnv1a32_hex(
    "\{workspace_urn}\u{0}\{adapter.as_str()}\u{0}\{origin_key}",
  )
  { urn: "\{intent_urn_prefix}\{slug}-\{digest}", }
}

///|
/// Returns the full URN text.
pub fn IntentId::as_str(self : IntentId) -> String {
  self.urn
}

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

///|
/// Reason why an `IntentTitle` failed validation.
#derive(Eq, Debug)
pub(all) enum IntentTitleRule {
  Empty
  TooLong
  ControlCharacter
}

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

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

///|
/// Parse error for `IntentTitle`.
#derive(Eq, Debug)
pub suberror IntentTitleError {
  InvalidIntentTitle(input~ : String, rule~ : IntentTitleRule)
}

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

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

///|
/// Trimmed non-empty single-line title (1..200 Unicode scalar values, no
/// control characters).
#derive(Eq, Compare, Debug)
pub struct IntentTitle {
  priv text : String
}

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

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

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

///|
/// Parses a trimmed single-line title.
pub fn IntentTitle::IntentTitle(
  raw : String,
) -> IntentTitle raise IntentTitleError {
  for ch in raw {
    let cp = ch.to_int()
    if cp < 0x20 || cp == 0x7F {
      raise InvalidIntentTitle(input=raw, rule=ControlCharacter)
    }
  }
  let trimmed = raw.trim(chars=" ").to_owned()
  if trimmed.is_empty() {
    raise InvalidIntentTitle(input=raw, rule=Empty)
  }
  let mut scalars = 0
  for _ in trimmed {
    scalars += 1
    if scalars > 200 {
      raise InvalidIntentTitle(input=raw, rule=TooLong)
    }
  }
  { text: trimmed, }
}

///|
/// Returns the normalized title string.
pub fn IntentTitle::as_str(self : IntentTitle) -> String {
  self.text
}

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

///|
/// Reason why a `DocumentPath` failed confinement validation.
#derive(Eq, Debug)
pub(all) enum DocumentPathRule {
  Empty
  TooLong
  ControlCharacter
  BackslashNotAllowed
  ColonNotAllowed
  AbsolutePath
  EmptySegment
  DotSegment
  PathTraversal
}

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

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

///|
/// Parse error for `DocumentPath`.
#derive(Eq, Debug)
pub suberror DocumentPathError {
  InvalidDocumentPath(input~ : String, rule~ : DocumentPathRule)
}

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

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

///|
/// Normalized workspace-relative path guaranteed to remain lexically confined
/// inside its workspace root (1..256 Unicode scalar values).
#derive(Eq, Compare, Hash, Debug)
pub struct DocumentPath {
  priv value : String
}

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

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

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

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

///|
/// Parses a workspace-relative document path, rejecting traversal, drive
/// letters, backslashes, leading slashes, empty segments, and control chars.
pub fn DocumentPath::DocumentPath(
  raw : String,
) -> DocumentPath raise DocumentPathError {
  if raw.is_empty() {
    raise InvalidDocumentPath(input=raw, rule=Empty)
  }
  let mut scalars = 0
  for ch in raw {
    scalars += 1
    if scalars > 256 {
      raise InvalidDocumentPath(input=raw, rule=TooLong)
    }
    let cp = ch.to_int()
    if cp < 0x20 || cp == 0x7F {
      raise InvalidDocumentPath(input=raw, rule=ControlCharacter)
    }
    if ch == '\\' {
      raise InvalidDocumentPath(input=raw, rule=BackslashNotAllowed)
    }
    if ch == ':' {
      raise InvalidDocumentPath(input=raw, rule=ColonNotAllowed)
    }
  }
  if raw.has_prefix("/") {
    raise InvalidDocumentPath(input=raw, rule=AbsolutePath)
  }
  for seg_view in raw.split("/") {
    let seg = seg_view.to_owned()
    if seg.is_empty() {
      raise InvalidDocumentPath(input=raw, rule=EmptySegment)
    }
    if seg == "." {
      raise InvalidDocumentPath(input=raw, rule=DotSegment)
    }
    if seg == ".." {
      raise InvalidDocumentPath(input=raw, rule=PathTraversal)
    }
  }
  { value: raw, }
}

///|
/// Returns the normalized relative path string.
pub fn DocumentPath::as_str(self : DocumentPath) -> String {
  self.value
}

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