import SwiftSyntax

/// A `@JS init` collected for direct JSI binding. A shared-object type has at most one (JS classes
/// have a single constructor). Instead of a `Constructor { … }` DSL entry, the macro synthesizes an
/// override of `SharedObject._constructSharedObject(...)` that decodes the JS arguments and returns a
/// fresh instance; unlike the method/property bindings it produces the native instance rather than
/// recovering one. Like a function, it can take the JavaScript runtime as its last parameter.
internal struct JSConstructor {
  /// The parameters that take JavaScript arguments, without the runtime parameter.
  let parameters: [FunctionParameterSyntax]
  /// The label of the parameter that takes the JavaScript runtime, or `nil` when the initializer has
  /// none.
  private let runtimeLabel: String?

  init(initDecl: InitializerDeclSyntax) {
    let declaredParameters = initDecl.signature.parameterClause.parameters
    self.parameters = declaredParameters.filter { !isRuntimeParameter($0) }
    self.runtimeLabel = declaredParameters.first(where: isRuntimeParameter)?.firstName.text
  }

  /// The body statements, indented with `indent`: arity guard, per-argument decode through
  /// `JavaScriptDecodable.decode` on a zero-copy `arguments.unownedValue(at:)` (the arity guard proves
  /// each index is in bounds) or a wrapper for a closure argument, then `return <Type>(label: arg0, …)`.
  private func bodyStatements(typeName: String, indent: String) -> String {
    var lines: [String] = []

    lines.append(
      """
      guard arguments.count == \(parameters.count) else {
        throw Exceptions.ArgumentsRangeMismatch((functionName: "\(typeName)", received: arguments.count, required: \(parameters.count), maximum: \(parameters.count)))
      }
      """
    )

    var callArguments: [String] = []
    for (index, parameter) in parameters.enumerated() {
      lines.append(
        contentsOf: argumentDecodeStatements(
          type: parameter.type,
          into: "arg\(index)",
          from: "arguments.unownedValue(at: \(index))"
        )
      )

      let label = parameter.firstName.text
      callArguments.append(label == "_" ? "arg\(index)" : "\(label): arg\(index)")
    }
    if let runtimeLabel {
      callArguments.append(runtimeLabel == "_" ? "runtime" : "\(runtimeLabel): runtime")
    }

    lines.append("return \(typeName)(\(callArguments.joined(separator: ", ")))")

    return
      lines
      .flatMap { $0.split(separator: "\n", omittingEmptySubsequences: false) }
      .map { indent + $0 }
      .joined(separator: "\n")
  }

  /// Builds an instance from the JS arguments. Overrides the base `SharedObject` class method; returns
  /// the concrete instance, which promotes to the base `SharedObject?` return type.
  ///
  /// A subclass without a `@JS init` of its own inherits this override, and would construct an instance
  /// of this class instead of the subclass. Unless the class is `final`, the override returns `nil` when
  /// called on a subclass, so core reports that the subclass has no JavaScript constructor.
  func buildConstructor(typeName: String, access: String, isFinal: Bool) -> DeclSyntax {
    let subclassGuard =
      isFinal
      ? ""
      : """
        guard self == \(typeName).self else {
          return nil
        }

      """
    return """
      @JavaScriptActor
      \(raw: access) override class func _constructSharedObject(this: borrowing JavaScriptValue, arguments: borrowing JavaScriptValuesBuffer, in runtime: JavaScriptRuntime) throws -> SharedObject? {
      \(raw: subclassGuard)\(raw: bodyStatements(typeName: typeName, indent: "  "))
      }
      """
  }
}
