// Generator configuration (YAML + programmatic / CLI overrides, plan 5.7).

///|
/// Configuration parsing or validation error.
#derive(Debug, Eq)
pub(all) suberror ConfigError {
  /// Config YAML could not be parsed.
  InvalidYaml(String)
  /// A config field failed semantic or cross-field validation.
  InvalidField(field~ : String, message~ : String)
}

///|
/// Configuration controlling client module layout, naming, enum policy,
/// tri-state nullability, format overrides, and ignored paths.
#derive(Debug, Eq)
pub(all) struct GeneratorConfig {
  /// Target MoonBit module name (e.g. `"acme/my_client"`).
  module_name : String
  /// Target module version in emitted `moon.mod`.
  module_version : String
  /// Optional module description (falls back to OpenAPI `info.description` or title).
  description : String?
  /// Optional repository URL in emitted `moon.mod`.
  repository : String?
  /// SPDX license identifier in emitted `moon.mod`.
  license : String
  /// Package discovery keywords in emitted `moon.mod`.
  keywords : Array[String]
  /// Optional fallback base URL used in `ClientConfig::default()` when the
  /// OpenAPI document omits `servers:` (or to override the default server URL).
  default_base_url : String?
  /// Runtime module dependency string (`"vigoo/openapi_client_runtime@0.1.0"`).
  runtime_package : String
  /// `moonbitlang/x` dependency string when `uuid` or `time` is used.
  x_package : String
  /// Name of the generated client struct (e.g. `"Client"`).
  client_name : String
  /// Name of the generated client suberror type (e.g. `"ApiError"`).
  error_name : String
  /// Add an `Unknown(String)` fallback variant to string enums.
  open_string_enums : Bool
  /// Add an `Unknown(@cjson.Json)` fallback variant to tagged unions.
  open_tagged_unions : Bool
  /// Use tri-state `NullableField[T]` (`Absent | Null | Value(T)`) for
  /// optional-nullable fields instead of collapsing to `T?`.
  tri_state : Bool
  /// Override OpenAPI `format` mappings (e.g. `"date-time" -> "String"`,
  /// `"uuid" -> "String"`).
  format_overrides : Map[String, String]
  /// OpenAPI paths to exclude from client generation. Entries ending with `*`
  /// act as prefix patterns; others match exact paths.
  ignored_paths : Array[String]
  /// Umbrella tags de-prioritized during tag grouping.
  global_tags : Array[String]
  /// Rename generated model types (`ir_name -> custom_pascal_name`).
  type_renames : Map[String, String]
  /// Rename generated client methods (`operationId -> custom_snake_name`).
  operation_renames : Map[String, String]
  /// Optional license header comment lines placed at the top of generated files.
  license_header : Array[String]
  /// Split `model/` into semantic operation-group files (`model/shared.mbt` +
  /// `model/.mbt`) once type count exceeds this threshold (`0` = always
  /// single `model/types.mbt`).
  model_split_threshold : Int32
  /// Emit generated `gentests/` subpackage covering schema `example` round-trips
  /// and mock-transport tests for every operation.
  emit_tests : Bool
  /// Emit `validate(self) -> Array[String]` methods on model structs enforcing
  /// OpenAPI validation keywords (`minimum`, `maxLength`, `minItems`, etc.).
  emit_validators : Bool
  /// Emit typed `Error` enums with `from_api_error(status~, body~)` helpers
  /// for operations declaring `4xx`/`5xx`/`4XX`/`5XX`/`default` error schemas.
  emit_typed_errors : Bool
}

///|
/// Default generator configuration for `module_name`.
pub fn GeneratorConfig::default(
  module_name~ : String = "example/api_client",
) -> GeneratorConfig {
  {
    module_name,
    module_version: "0.1.0",
    description: None,
    repository: None,
    license: "Apache-2.0",
    keywords: [],
    default_base_url: None,
    runtime_package: "vigoo/openapi_client_runtime@0.1.0",
    x_package: "moonbitlang/x@0.5.9",
    client_name: "Client",
    error_name: "ApiError",
    open_string_enums: false,
    open_tagged_unions: false,
    tri_state: false,
    format_overrides: Map([]),
    ignored_paths: [],
    global_tags: [],
    type_renames: Map([]),
    operation_renames: Map([]),
    license_header: [],
    model_split_threshold: 40,
    emit_tests: false,
    emit_validators: false,
    emit_typed_errors: false,
  }
}

///|
fn is_valid_pascal_ident(s : String) -> Bool {
  if s.is_empty() {
    return false
  }
  let c0 = s[0]
  if !(c0 >= 'A' && c0 <= 'Z') {
    return false
  }
  for i in 1..= 'A' && c <= 'Z') ||
      (c >= 'a' && c <= 'z') ||
      (c >= '0' && c <= '9') ||
      c == '_'
    if !ok {
      return false
    }
  }
  true
}

///|
fn is_valid_value_ident(s : String) -> Bool {
  if s.is_empty() || s == "_" || @name.is_keyword(s) {
    return false
  }
  let c0 = s[0]
  if !((c0 >= 'a' && c0 <= 'z') || c0 == '_') {
    return false
  }
  for i in 1..= 'a' && c <= 'z') ||
      (c >= 'A' && c <= 'Z') ||
      (c >= '0' && c <= '9') ||
      c == '_'
    if !ok {
      return false
    }
  }
  true
}

///|
fn is_valid_module_seg(s : String) -> Bool {
  if s.is_empty() {
    return false
  }
  for i in 0..= 'a' && c <= 'z') ||
      (c >= 'A' && c <= 'Z') ||
      (c >= '0' && c <= '9') ||
      c == '_' ||
      c == '-'
    if !ok {
      return false
    }
  }
  true
}

///|
fn is_valid_module_name(s : String) -> Bool {
  let parts : Array[String] = s.split("/").map(v => v.to_owned()).collect()
  parts.length() == 2 &&
  is_valid_module_seg(parts[0]) &&
  is_valid_module_seg(parts[1])
}

///|
fn has_whitespace_or_control(s : String) -> Bool {
  for ch in s {
    let code = ch.to_int()
    if code <= 0x20 || code == 0x7F {
      return true
    }
  }
  false
}

///|
fn is_reserved_builtin_type(name : String) -> Bool {
  match name {
    "Self"
    | "Unit"
    | "Bool"
    | "Byte"
    | "Char"
    | "Int"
    | "Int16"
    | "Int32"
    | "Int64"
    | "UInt"
    | "UInt16"
    | "UInt32"
    | "UInt64"
    | "Float"
    | "Double"
    | "String"
    | "Bytes"
    | "Option"
    | "Result"
    | "Array"
    | "FixedArray"
    | "ReadOnlyArray"
    | "Map"
    | "Json"
    | "Error"
    | "BigInt"
    | "Ref"
    | "Iter"
    | "Iter2"
    | "StringView"
    | "BytesView"
    | "ArrayView"
    | "StringBuilder"
    | "UninitializedArray"
    | "FuncRef" => true
    _ => false
  }
}

///|
/// Validate all fields and cross-field invariants of `GeneratorConfig`.
/// Called automatically by `GeneratorConfig::from_yaml` and after CLI overrides.
pub fn GeneratorConfig::validate(
  self : GeneratorConfig,
) -> Unit raise ConfigError {
  if !is_valid_module_name(self.module_name) {
    raise InvalidField(
      field="module_name",
      message="must be `/` with ASCII alphanumeric/`_`/`-` characters, got '\{self.module_name}'",
    )
  }
  if self.module_version.is_empty() ||
    has_whitespace_or_control(self.module_version) {
    raise InvalidField(
      field="module_version",
      message="must be a non-empty version string without whitespace or control characters",
    )
  }
  if self.runtime_package.is_empty() ||
    has_whitespace_or_control(self.runtime_package) ||
    !self.runtime_package.contains("@") {
    raise InvalidField(
      field="runtime_package",
      message="must be a `/@` dependency spec, got '\{self.runtime_package}'",
    )
  }
  if self.x_package.is_empty() ||
    has_whitespace_or_control(self.x_package) ||
    !self.x_package.contains("@") {
    raise InvalidField(
      field="x_package",
      message="must be a `/@` dependency spec, got '\{self.x_package}'",
    )
  }
  if !is_valid_pascal_ident(self.client_name) {
    raise InvalidField(
      field="client_name",
      message="must be a valid PascalCase identifier, got '\{self.client_name}'",
    )
  }
  if !is_valid_pascal_ident(self.error_name) {
    raise InvalidField(
      field="error_name",
      message="must be a valid PascalCase identifier, got '\{self.error_name}'",
    )
  }
  if self.client_name == self.error_name {
    raise InvalidField(
      field="error_name",
      message="error_name must differ from client_name ('\{self.client_name}')",
    )
  }
  if self.client_name == "ClientConfig" ||
    self.client_name == "Auth" ||
    self.client_name == "Server" ||
    self.client_name == "NullableField" ||
    is_reserved_builtin_type(self.client_name) {
    raise InvalidField(
      field="client_name",
      message="client_name '\{self.client_name}' collides with reserved generated or builtin type",
    )
  }
  if self.error_name == "ClientConfig" ||
    self.error_name == "Auth" ||
    self.error_name == "Server" ||
    self.error_name == "NullableField" ||
    is_reserved_builtin_type(self.error_name) {
    raise InvalidField(
      field="error_name",
      message="error_name '\{self.error_name}' collides with reserved generated or builtin type",
    )
  }
  if self.model_split_threshold < 0 {
    raise InvalidField(
      field="model_split_threshold",
      message="must be a non-negative integer, got \{self.model_split_threshold}",
    )
  }
  for i, line in self.license_header {
    if line.contains("\n") || line.contains("\r") {
      raise InvalidField(
        field="license_header[\{i}]",
        message="license header lines must not contain embedded newlines",
      )
    }
  }
  for k, v in self.format_overrides {
    if k.trim().is_empty() ||
      v.trim().is_empty() ||
      v.contains("\n") ||
      v.contains("\r") {
      raise InvalidField(
        field="format_overrides.\{k}",
        message="format override key and target type must be non-empty single-line strings",
      )
    }
  }
  let seen_type_targets : Map[String, String] = Map([])
  for k, v in self.type_renames {
    if !is_valid_pascal_ident(v) || is_reserved_builtin_type(v) {
      raise InvalidField(
        field="type_renames.\{k}",
        message="invalid or reserved target type name '\{v}'",
      )
    }
    match seen_type_targets.get(v) {
      Some(prev) =>
        raise InvalidField(
          field="type_renames.\{k}",
          message="duplicate target type name '\{v}' (already mapped from '\{prev}')",
        )
      None => seen_type_targets[v] = k
    }
  }
  let seen_op_targets : Map[String, String] = Map([])
  for k, v in self.operation_renames {
    if !is_valid_value_ident(v) {
      raise InvalidField(
        field="operation_renames.\{k}",
        message="must be a valid non-keyword lowercase MoonBit identifier, got '\{v}'",
      )
    }
    match seen_op_targets.get(v) {
      Some(prev) =>
        raise InvalidField(
          field="operation_renames.\{k}",
          message="duplicate target method name '\{v}' (already mapped from '\{prev}')",
        )
      None => seen_op_targets[v] = k
    }
  }
}

///|
pub fn GeneratorConfig::to_ir_options(self : GeneratorConfig) -> @ir.IrOptions {
  {
    open_string_enums: self.open_string_enums,
    open_tagged_unions: self.open_tagged_unions,
    global_tags: self.global_tags.copy(),
  }
}

///|
pub fn GeneratorConfig::is_path_ignored(
  self : GeneratorConfig,
  path : String,
) -> Bool {
  for pattern in self.ignored_paths {
    if pattern.has_suffix("*") {
      let prefix = pattern[0:pattern.length() - 1].to_owned()
      if path.has_prefix(prefix) {
        return true
      }
    } else if path == pattern {
      return true
    }
  }
  false
}

///|
pub fn GeneratorConfig::resolve_type_name(
  self : GeneratorConfig,
  name : String,
) -> String {
  self.type_renames.get(name).unwrap_or(name)
}

///|
pub fn GeneratorConfig::resolve_operation_name(
  self : GeneratorConfig,
  operation_id : String,
  default_method : String,
) -> String {
  self.operation_renames.get(operation_id).unwrap_or(default_method)
}

///|
pub fn GeneratorConfig::format_override(
  self : GeneratorConfig,
  format : String,
) -> String? {
  self.format_overrides.get(format)
}

///|
fn expect_string(node : @spec.Node, field : String) -> String raise ConfigError {
  match node.as_str() {
    Some(s) => s
    None => raise InvalidField(field~, message="expected string")
  }
}

///|
fn expect_non_empty_string(
  node : @spec.Node,
  field : String,
) -> String raise ConfigError {
  let s = expect_string(node, field)
  if s.trim().is_empty() {
    raise InvalidField(field~, message="must not be empty")
  }
  s
}

///|
fn expect_optional_string(
  node : @spec.Node,
  field : String,
) -> String? raise ConfigError {
  if node is @spec.Null {
    None
  } else {
    Some(expect_string(node, field))
  }
}

///|
fn expect_bool(node : @spec.Node, field : String) -> Bool raise ConfigError {
  match node.as_bool() {
    Some(b) => b
    None => raise InvalidField(field~, message="expected boolean")
  }
}

///|
fn expect_int32(node : @spec.Node, field : String) -> Int32 raise ConfigError {
  match node.as_int32() {
    Some(n) => n
    None => raise InvalidField(field~, message="expected integer")
  }
}

///|
fn expect_string_array(
  node : @spec.Node,
  field : String,
) -> Array[String] raise ConfigError {
  match node.as_array() {
    Some(items) => {
      let out : Array[String] = []
      for i, item in items {
        out.push(expect_string(item, "\{field}[\{i}]"))
      }
      out
    }
    None => raise InvalidField(field~, message="expected array of strings")
  }
}

///|
fn expect_string_map(
  node : @spec.Node,
  field : String,
) -> Map[String, String] raise ConfigError {
  match node.as_object() {
    Some(obj) => {
      let out : Map[String, String] = Map([])
      for entry in obj.entries {
        let (k, v) = entry
        out[k] = expect_string(v, "\{field}.\{k}")
      }
      out
    }
    None => raise InvalidField(field~, message="expected string map")
  }
}

///|
/// Parse a YAML configuration file into `GeneratorConfig`.
/// Unknown top-level keys raise `ConfigError::InvalidField` so typos fail fast.
pub fn GeneratorConfig::from_yaml(
  text : String,
) -> GeneratorConfig raise ConfigError {
  if text.trim().is_empty() {
    return GeneratorConfig::default()
  }
  let (root, issues) = @spec.parse_yaml_source(text) catch {
    @spec.SpecError(msg) => raise InvalidYaml(msg)
  }
  if !issues.is_empty() {
    raise InvalidYaml(issues[0].message)
  }
  if root is @spec.Null {
    return GeneratorConfig::default()
  }
  let entries = match root.as_object() {
    Some(obj) => obj.entries
    None => raise InvalidField(field="", message="expected YAML mapping")
  }
  let mut cfg = GeneratorConfig::default()
  for entry in entries {
    let (key, value) = entry
    match key {
      "module" | "module_name" =>
        cfg = { ..cfg, module_name: expect_non_empty_string(value, key), }
      "version" | "module_version" =>
        cfg = { ..cfg, module_version: expect_non_empty_string(value, key), }
      "description" =>
        cfg = { ..cfg, description: expect_optional_string(value, key), }
      "repository" =>
        cfg = { ..cfg, repository: expect_optional_string(value, key), }
      "license" => cfg = { ..cfg, license: expect_string(value, key), }
      "keywords" => cfg = { ..cfg, keywords: expect_string_array(value, key), }
      "default_base_url" =>
        cfg = { ..cfg, default_base_url: expect_optional_string(value, key), }
      "runtime_package" =>
        cfg = { ..cfg, runtime_package: expect_non_empty_string(value, key), }
      "x_package" =>
        cfg = { ..cfg, x_package: expect_non_empty_string(value, key), }
      "client_name" =>
        cfg = { ..cfg, client_name: expect_non_empty_string(value, key), }
      "error_name" =>
        cfg = { ..cfg, error_name: expect_non_empty_string(value, key), }
      "open_string_enums" | "open_enums" =>
        cfg = { ..cfg, open_string_enums: expect_bool(value, key), }
      "open_tagged_unions" | "open_unions" =>
        cfg = { ..cfg, open_tagged_unions: expect_bool(value, key), }
      "enum_policy" => {
        let policy = expect_string(value, key).to_lower()
        match policy {
          "open" => cfg = { ..cfg, open_string_enums: true, }
          "closed" => cfg = { ..cfg, open_string_enums: false, }
          _ =>
            raise InvalidField(
              field=key,
              message="expected 'open' or 'closed', got '\{policy}'",
            )
        }
      }
      "tri_state" => cfg = { ..cfg, tri_state: expect_bool(value, key), }
      "format_overrides" =>
        cfg = { ..cfg, format_overrides: expect_string_map(value, key), }
      "ignored_paths" =>
        cfg = { ..cfg, ignored_paths: expect_string_array(value, key), }
      "global_tags" =>
        cfg = { ..cfg, global_tags: expect_string_array(value, key), }
      "type_renames" =>
        cfg = { ..cfg, type_renames: expect_string_map(value, key), }
      "operation_renames" =>
        cfg = { ..cfg, operation_renames: expect_string_map(value, key), }
      "license_header" => {
        let lines = expect_string_array(value, key)
        for i, line in lines {
          if line.contains("\n") || line.contains("\r") {
            raise InvalidField(
              field="\{key}[\{i}]",
              message="license header lines must not contain embedded newlines",
            )
          }
        }
        cfg = { ..cfg, license_header: lines, }
      }
      "model_split_threshold" => {
        let n = expect_int32(value, key)
        if n < 0 {
          raise InvalidField(
            field=key,
            message="must be a non-negative integer, got \{n}",
          )
        }
        cfg = { ..cfg, model_split_threshold: n, }
      }
      "emit_tests" => cfg = { ..cfg, emit_tests: expect_bool(value, key), }
      "emit_validators" =>
        cfg = { ..cfg, emit_validators: expect_bool(value, key), }
      "emit_typed_errors" =>
        cfg = { ..cfg, emit_typed_errors: expect_bool(value, key), }
      _ =>
        raise InvalidField(
          field=key,
          message="unknown configuration key '\{key}'",
        )
    }
  }
  cfg.validate()
  cfg
}