///|
/// Compile-time zero-reflection DI (`#ciallo.provider`) generator powered by `moonbitlang/parser` AST.

///|
#derive(Debug, Eq)
pub(all) struct ProviderSpec {
  file : String
  line : Int32
  fn_name : String
  is_async : Bool
  params : Array[(String, String)]
  labelled_params : Array[Bool]
  return_type : String
}

///|
fn is_wire_ignored_file(path : String) -> Bool {
  path.has_suffix("_test.mbt") ||
  path.has_suffix(".gen.mbt") ||
  path.has_suffix(".orm_gen.mbt") ||
  path.has_suffix(".wire_gen.mbt")
}

///|
fn has_provider_attr(attrs : Array[String]) -> Bool {
  for a in attrs {
    if a == "#ciallo.provider" || a.has_prefix("#ciallo.provider(") {
      return true
    }
  }
  false
}

///|
/// Scans all `#ciallo.provider` functions across package files using `moonbitlang/parser` AST
/// (deterministically ordered by filename; automatically skips `*_test.mbt` and generated files).
pub fn parse_wire_providers(
  files : Array[(String, String)],
) -> Array[ProviderSpec] raise GenError {
  let sorted = files.copy()
  sorted.sort_by((a, b) => a.0.compare(b.0))
  let out : Array[ProviderSpec] = []
  for pair in sorted {
    let (file, src) = pair
    if is_wire_ignored_file(file) {
      continue
    }
    let impls = parse_mbt_ast(src, file)
    for item in impls {
      match item {
        @syntax.Impl::TopFuncDef(fun_decl~, ..) => {
          let attrs = collect_attr_strings(fun_decl.attrs, fun_decl.doc)
          if !has_provider_attr(attrs) {
            continue
          }
          let line = fun_decl.loc.start.lnum
          let fn_name = match fun_decl.type_name {
            Some(tn) => "\{render_long_ident(tn.name)}::\{fun_decl.name.name}"
            None => fun_decl.name.name
          }
          let is_async = fun_decl.is_async is Some(_)
          let params : Array[(String, String)] = []
          let labelled_params : Array[Bool] = []
          match fun_decl.decl_params {
            Some(plist) => {
              let mut cur = plist
              for ;; {
                match cur {
                  @list.List::Empty => break
                  @list.List::More(p, tail~) => {
                    let (binder_opt, ty_opt, is_labelled) : (
                      @syntax.Binder?,
                      @syntax.Type?,
                      Bool,
                    ) = match p {
                      @syntax.Parameter::Positional(binder~, ty~) =>
                        (Some(binder), ty, false)
                      @syntax.Parameter::Labelled(binder~, ty~)
                      | @syntax.Parameter::Optional(binder~, ty~, ..)
                      | @syntax.Parameter::QuestionOptional(binder~, ty~) =>
                        (Some(binder), ty, true)
                      @syntax.Parameter::DiscardPositional(..) =>
                        (None, None, false)
                    }
                    match binder_opt {
                      Some(binder) =>
                        match ty_opt {
                          Some(t) => {
                            check_syntax_type_canonical(
                              t,
                              file,
                              line,
                              as_unsupported=true,
                            )
                            params.push((binder.name, render_syntax_type(t)))
                            labelled_params.push(is_labelled)
                          }
                          None =>
                            raise GenError::InvalidSource(
                              file~,
                              line~,
                              message="missing explicit type annotation on parameter '\{binder.name}' in #ciallo.provider '\{fn_name}'",
                            )
                        }
                      None => ()
                    }
                    cur = tail
                  }
                }
              }
            }
            None => ()
          }
          let return_type = match fun_decl.return_type {
            Some(rt) => {
              check_syntax_type_canonical(rt, file, line, as_unsupported=true)
              render_syntax_type(rt)
            }
            None =>
              raise GenError::InvalidSource(
                file~,
                line~,
                message="missing '-> ReturnType' in #ciallo.provider function '\{fn_name}'",
              )
          }
          out.push({
            file,
            line,
            fn_name,
            is_async,
            params,
            labelled_params,
            return_type,
          })
        }
        _ => ()
      }
    }
  }
  out
}

///|
/// Compile-time static DI topological sort + cycle detection + zero-reflection container wiring.
pub fn generate_wire_source(
  files : Array[(String, String)],
  wire_fn_name~ : String = "wire_container",
) -> String raise GenError {
  let providers = parse_wire_providers(files)
  let by_type : Map[String, Int32] = Map([])
  for idx in 0.. {
          adj[dep_idx].push(idx)
          indegree[idx] = indegree[idx] + 1
        }
        None =>
          if !seen_ext.contains(pty) {
            seen_ext[pty] = true
            external_inputs.push((pname, pty))
          }
      }
    }
  }

  // Deterministic Kahn topological sort
  let order : Array[Int32] = []
  let visited : FixedArray[Bool] = FixedArray::make(n, false)
  while order.length() < n {
    let mut picked : Int32 = -1
    for i in 0.. ")
      raise GenError::InvalidSource(
        file=first_file,
        line=first_line,
        message="cyclic #ciallo.provider dependency detected among: \{desc}",
      )
    }
    visited[picked] = true
    order.push(picked)
    for nxt in adj[picked] {
      indegree[nxt] = indegree[nxt] - 1
    }
  }

  let has_async = providers.iter().any(p => p.is_async)
  let sb = StringBuilder()
  sb.write_string("// Code generated by ciallo-gen wire. DO NOT EDIT.\n\n")

  sb.write_string("///|\npub(all) struct WiredContainer {\n")
  for p in providers {
    let field_name = sanitize_mbt_field_ident(to_snake_case(p.return_type))
    sb.write_string("  \{field_name} : \{p.return_type}\n")
  }
  sb.write_string("}\n\n")

  let async_kw = if has_async { "async " } else { "" }
  let ext_sig = external_inputs.map(e => "\{e.0}~ : \{e.1}").join(", ")
  sb.write_string(
    "///|\npub \{async_kw}fn \{wire_fn_name}(\{ext_sig}) -> WiredContainer {\n",
  )

  let var_of_type : Map[String, String] = Map([])
  for ext in external_inputs {
    var_of_type[ext.1] = ext.0
  }
  for idx in order {
    let p = providers[idx]
    let vname = "dep_\{sanitize_mbt_field_ident(to_snake_case(p.return_type))}"
    var_of_type[p.return_type] = vname
    let call_args : Array[String] = []
    for i in 0.. String {
  let sb = StringBuilder()
  for ch in raw {
    let c = ch.to_int()
    if (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || ch == '_' {
      sb.write_char(ch)
    } else if c >= 65 && c <= 90 {
      sb.write_char((c + 32).unsafe_to_char())
    } else {
      sb.write_char('_')
    }
  }
  let s = sb.to_string()
  if s.is_empty() {
    "dep"
  } else {
    s
  }
}