import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxMacros

/// Accessor macro applied to a function-typed `var` on a module or shared object, turning it into a
/// typed JavaScript event. A function-typed `var` can't be a stored property without an initializer,
/// so the macro expands it into a computed getter returning a closure that dispatches by name into
/// the `EventEmitter` `emit` overloads (core conforms both `BaseModule` and `SharedObject` to that
/// protocol, so `self.emit` resolves on each):
///
///   @Event
///   var onProgress: (ProgressEvent) -> Void
///   // expands to:
///   var onProgress: (ProgressEvent) -> Void {
///     get {
///       { [weak self] payload in self?.emit(event: "progress", payload: payload) }
///     }
///   }
///
/// A no-payload event (`() -> Void`) dispatches through the dedicated `emit(event:)` overload.
/// The JS event name defaults to the property name with the conventional `on` prefix stripped
/// (see `defaultEventName(for:)`); `@Event("customName")` overrides it verbatim.
///
/// The closure captures `self` **weakly**: it's usually invoked inline (`self.onProgress(…)`), but an
/// author may store it or hand it to a delegate, and a strong capture would then extend the module's
/// lifetime. After the emitter deallocates the closure silently no-ops, which matches what `emit`
/// already does once the runtime is gone.
///
/// The synthesized property is deliberately **not** isolated to `@JavaScriptActor`, unlike `@JS`
/// members: `emit` is itself non-isolated and schedules the dispatch onto the JS thread internally,
/// so the event is callable from any thread or isolation with no actor hop at the call site. It is
/// also self-contained: `@ExpoModule`/`@SharedObject` don't register `@Event` members anywhere. They
/// read the event names only to warn when two events share one (see `diagnoseEventNameCollisions`).
///
/// Two options change how the event is dispatched, and each one calls its own `EventEmitter` method,
/// which is callable from any thread as well:
/// - `@Event(.inline)` calls `emitInline`: on the JS thread the listeners run before the call
///   returns; on any other thread the event is scheduled, the same as `emit`. It never blocks.
/// - `@Event(.blocking)` calls `emitBlocking`: the listeners run before the call returns on any
///   thread, so a call from another thread blocks until the JS thread runs them.
///
/// As a **peer**, the macro emits a never-called conformance assertion (see
/// `TypeConformanceAssertion.swift`) checking that the payload type is JS-convertible and that the
/// enclosing type conforms to `EventEmitter`, so both failure modes surface as clear conformance
/// errors on the user's own declaration.
public struct EventMacro: AccessorMacro {
  public static func expansion(
    of node: AttributeSyntax,
    providingAccessorsOf declaration: some DeclSyntaxProtocol,
    in context: some MacroExpansionContext
  ) throws -> [AccessorDeclSyntax] {
    let event = try validatedEvent(of: node, on: declaration)
    // The closure's parameter and return types are inferred from the property's declared type
    // through the getter, so the body never has to spell the payload type. The dispatch option
    // picks the `EventEmitter` method. A payload that holds a tuple can't conform to the payload
    // protocols, so it's passed with a closure that encodes it.
    let emitMethod = event.dispatch.emitMethod
    let closure: String
    if let tuple = event.payloadType.flatMap({ tupleConversion(of: $0) }) {
      let encode = encoderClosure(encoding: tuple.encodeCall(of: "value", into: "slot"))
      closure =
        "{ [weak self] payload in self?.\(emitMethod)(event: \"\(event.jsName)\", payload: payload, encode: \(encode)) }"
    } else if event.hasPayload {
      closure = "{ [weak self] payload in self?.\(emitMethod)(event: \"\(event.jsName)\", payload: payload) }"
    } else {
      closure = "{ [weak self] in self?.\(emitMethod)(event: \"\(event.jsName)\") }"
    }
    return [
      """
      get {
        \(raw: closure)
      }
      """
    ]
  }
}

extension EventMacro: PeerMacro {
  public static func expansion(
    of node: AttributeSyntax,
    providingPeersOf declaration: some DeclSyntaxProtocol,
    in context: some MacroExpansionContext
  ) throws -> [DeclSyntax] {
    // Diagnostics are owned by the accessor expansion; an invalid declaration silently emits no
    // peer here so each error is reported once.
    guard let event = try? validatedEvent(of: node, on: declaration) else {
      return []
    }
    // One nested helper asserts everything in a single call: the payload type is JS-convertible
    // (the first parameter, dropped for no-payload events and known-conforming primitives) and the
    // enclosing type can emit (the last parameter, always present since any `@Event` dispatches
    // through `self.emit`). Named after the member so the member shows up in either diagnostic,
    // and asserting the enclosing type by its spelled name so the conformance error names the
    // user's type rather than 'Self'.
    //
    // A payload that holds a tuple is encoded element by element (see `TupleConversion`), so the types
    // in it are asserted `JavaScriptEncodable`, which the encode closure needs, in its place.
    // `emitInline` and `emitBlocking` take only `JavaScriptEncodable` payloads, so with those options
    // the payload is asserted `JavaScriptEncodable` too.
    let name = event.swiftName
    let tupleElementTypes = event.payloadType.flatMap { tupleConversion(of: $0)?.conformingTypes }
    let payloadConstraint =
      tupleElementTypes == nil && event.dispatch == .scheduled
      ? jsConvertibleProtocolName : javaScriptEncodableProtocolName
    let payloads =
      tupleElementTypes.map { distinctAssertableTypes($0, constraint: payloadConstraint) }
      ?? event.payloadType.flatMap { assertableBoundaryType($0, constraint: payloadConstraint) }.map { [$0] } ?? []
    let owner = enclosingTypeName(in: context) ?? "Self"
    let emitterParameter = opaqueMetatypeParameter(constraint: eventEmitterProtocolName)
    let payloadParameters = payloads.map { _ in opaqueMetatypeParameter(constraint: payloadConstraint) }
    let helper = "func \(name)(\((payloadParameters + [emitterParameter]).joined(separator: ", "))) {}"
    let call = "\(name)(\((payloads + [owner]).map { "\($0).self" }.joined(separator: ", ")))"
    let peerName = derivedIdentifier(from: name, prefix: "_assertTypesConformance_")
    return [
      """
      private func \(raw: peerName)() {
      \(raw: helper)
      \(raw: call)
      }
      """
    ]
  }
}

/// What the expansions need to know about a validated `@Event` declaration: the property name, the
/// JS event name (after an `@Event("…")` override), and the payload type when the function type
/// takes one.
private struct EventMember {
  let swiftName: String
  let jsName: String
  /// The payload type as written, or `nil` for a no-payload `() -> Void` event.
  let payloadType: String?
  /// How the event is dispatched, from the `.inline` or `.blocking` option.
  let dispatch: EventDispatch

  var hasPayload: Bool {
    return payloadType != nil
  }
}

/// Validates the declaration `@Event` is attached to and reads the event out of it. The checks
/// mirror what the expansion relies on: a single-binding instance `var` (the macro synthesizes a
/// computed getter, so `let`, accessors, and initializers are all incompatible) whose type is a
/// function type returning `Void` with at most one payload parameter, which holds no closure.
private func validatedEvent(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol
) throws -> EventMember {
  guard let varDecl = declaration.as(VariableDeclSyntax.self) else {
    throw MacroExpansionErrorMessage("@Event can only be applied to a property")
  }
  if let jsAttribute = varDecl.attributes.firstAttribute(named: "JS") {
    throw jsAttributeDiagnostic(for: jsAttribute)
  }
  // The compiler also rejects accessor macros on a `let`, but with a generic message; this one says
  // what to do instead and carries the fix-it doing it. The synthesized property is getter-only, so
  // switching to `var` loses nothing.
  if varDecl.bindingSpecifier.tokenKind == .keyword(.let) {
    throw letBindingDiagnostic(for: varDecl)
  }
  if let typeLevelModifier = varDecl.modifiers.first(where: isTypeLevelModifier) {
    throw typeLevelModifierDiagnostic(for: typeLevelModifier)
  }
  guard varDecl.bindings.count == 1, let binding = varDecl.bindings.first,
    let identifier = binding.pattern.as(IdentifierPatternSyntax.self)
  else {
    throw MacroExpansionErrorMessage(
      "@Event must be applied to a single named property. Declare each event separately"
    )
  }
  if let initializer = binding.initializer {
    throw initialValueDiagnostic(for: initializer, in: binding, of: varDecl)
  }
  if binding.accessorBlock != nil {
    throw MacroExpansionErrorMessage(
      "@Event property cannot declare its own accessors: the macro synthesizes the getter"
    )
  }
  guard let functionType = underlyingFunctionType(of: binding.typeAnnotation?.type) else {
    throw MacroExpansionErrorMessage(
      "@Event property must declare a function type, such as '(Payload) -> Void' or '() -> Void'"
    )
  }
  guard isVoidReturn(functionType.returnClause.type) else {
    throw returnTypeDiagnostic(for: functionType.returnClause.type)
  }
  guard functionType.parameters.count <= 1 else {
    throw MacroExpansionErrorMessage(
      "@Event function type takes at most one payload parameter. Combine multiple values into a single record"
    )
  }
  // The payload is encoded to JavaScript, and a native closure can't be encoded.
  if let payloadClosure = functionType.parameters.first.flatMap({ firstFunctionType(in: $0.type) }) {
    throw DiagnosticsError(diagnostics: [
      Diagnostic(
        node: payloadClosure,
        message: EventDiagnosticMessage(
          "@Event payload can't hold a closure: the payload is encoded to JavaScript, and a native closure can't be encoded",
          id: "event-closure-payload"
        )
      )
    ])
  }

  let swiftName = identifier.identifier.text
  let dispatch = try eventDispatch(of: node)
  return EventMember(
    swiftName: swiftName,
    jsName: jsNameArgument(of: node) ?? defaultEventName(for: withoutBackticks(swiftName)),
    payloadType: functionType.parameters.first?.type.trimmedDescription,
    dispatch: dispatch
  )
}

/// How an `@Event` is dispatched to JavaScript, picked by its option.
private enum EventDispatch {
  case scheduled
  case inline
  case blocking

  var emitMethod: String {
    switch self {
    case .scheduled:
      return "emit"
    case .inline:
      return "emitInline"
    case .blocking:
      return "emitBlocking"
    }
  }
}

/// Reads the dispatch option of an `@Event` attribute. `.inline` and `.blocking` exclude each other.
private func eventDispatch(of node: AttributeSyntax) throws -> EventDispatch {
  let isInline = hasOption(node, named: "inline")
  let isBlocking = hasOption(node, named: "blocking")
  if isInline && isBlocking {
    throw conflictingOptionsDiagnostic(in: node)
  }
  if isInline {
    return .inline
  }
  if isBlocking {
    return .blocking
  }
  return .scheduled
}

/// The error for `@Event(.inline, .blocking)`, with a single Fix-It that removes the option written
/// last. One Fix-It (rather than one for each option) lets the `fix` command apply it, since it skips
/// a diagnostic with alternatives.
private func conflictingOptionsDiagnostic(in node: AttributeSyntax) -> DiagnosticsError {
  let message = EventDiagnosticMessage(
    "@Event can't be both '.inline' and '.blocking': '.blocking' also runs the listeners inline on the JS thread. Remove one of the options",
    id: "event-conflicting-options"
  )
  guard let arguments = node.arguments?.as(LabeledExprListSyntax.self),
    let index = arguments.lastIndex(where: { isDispatchOption($0.expression) })
  else {
    return DiagnosticsError(diagnostics: [Diagnostic(node: node, message: message)])
  }
  let removed = arguments[index]
  let optionName = removed.expression.as(MemberAccessExprSyntax.self)?.declName.baseName.text ?? "option"
  let fixIt = FixIt(
    message: EventFixItMessage("Remove '.\(optionName)'", id: "event-remove-option"),
    changes: [
      .replace(oldNode: Syntax(node), newNode: Syntax(removingArgument(removed, from: node)))
    ]
  )
  return DiagnosticsError(diagnostics: [Diagnostic(node: node, message: message, fixIts: [fixIt])])
}

/// True when the expression is the `.inline` or `.blocking` option (or `EventOptions.<option>`).
private func isDispatchOption(_ expression: ExprSyntax) -> Bool {
  guard let member = expression.as(MemberAccessExprSyntax.self) else {
    return false
  }
  let name = member.declName.baseName.text
  return name == "inline" || name == "blocking"
}

/// The JS name of an `@Event` property: the `@Event("…")` override, or the default name derived from
/// the property name. `nil` when the declaration isn't a single named property, which the macro reports.
internal func eventJSName(of varDecl: VariableDeclSyntax, attribute: AttributeSyntax) -> String? {
  guard varDecl.bindings.count == 1, let identifier = varDecl.bindings.first?.pattern.as(IdentifierPatternSyntax.self)
  else {
    return nil
  }
  return jsNameArgument(of: attribute) ?? defaultEventName(for: withoutBackticks(identifier.identifier.text))
}

// MARK: - Default event name

/// The default JS event name for a property: the Swift name with the conventional `on` prefix
/// stripped and the remainder decapitalized (`onStatusChange` → `statusChange`). The two sides
/// idiomatically want different names: the Swift property reads as invoking a handler
/// (`self.onStatusChange(…)`) and the prefix keeps it from colliding with a state property
/// (`status`), while JS listens by bare name (`addListener("statusChange")`, the Node/DOM idiom
/// that module and shared-object events follow). Names without the prefix (`statusChange`,
/// `online`) pass through verbatim, and an explicit `@Event("name")` override is never
/// transformed — that's also the escape hatch for legacy `onX` wire names.
private func defaultEventName(for swiftName: String) -> String {
  guard swiftName.hasPrefix("on") else {
    return swiftName
  }
  let rest = swiftName.dropFirst(2)
  guard let first = rest.first, first.isUppercase else {
    return swiftName
  }
  return decapitalized(String(rest))
}

/// Lowercases the leading uppercase run the way Swift's API importer does: a single leading
/// capital is lowercased (`StatusChange` → `statusChange`); a longer acronym run keeps its last
/// capital when a lowercase letter follows it, since that capital starts the next word
/// (`URLChange` → `urlChange`, `URL` → `url`).
private func decapitalized(_ name: String) -> String {
  let runEnd = name.firstIndex { !$0.isUppercase } ?? name.endIndex
  if name[..<runEnd].count > 1 && runEnd != name.endIndex {
    let lastCapital = name.index(before: runEnd)
    return name[..<lastCapital].lowercased() + name[lastCapital...]
  }
  return name[..<runEnd].lowercased() + name[runEnd...]
}

// MARK: - The `let` diagnostic

/// The error for `@Event let`, attached to the `let` keyword itself and carrying a fix-it that
/// replaces it with `var`. Unlike the other checks (plain thrown messages located at the attribute),
/// this one is a structured `Diagnostic` so Xcode can offer the one-click fix.
private func letBindingDiagnostic(for varDecl: VariableDeclSyntax) -> DiagnosticsError {
  let specifier = varDecl.bindingSpecifier
  let fixIt = FixIt(
    message: EventFixItMessage("Replace 'let' with 'var'", id: "event-let-to-var"),
    changes: [
      // Rewriting just the token's kind keeps its surrounding trivia (indentation, the space
      // before the property name) intact.
      .replace(
        oldNode: Syntax(specifier),
        newNode: Syntax(specifier.with(\.tokenKind, .keyword(.var)))
      )
    ]
  )
  let message = EventDiagnosticMessage(
    "@Event must be applied to a 'var': it expands into a computed property, which a 'let' cannot be. The synthesized property is read-only anyway",
    id: "event-on-let"
  )
  return DiagnosticsError(diagnostics: [
    Diagnostic(node: specifier, message: message, fixIts: [fixIt])
  ])
}

// MARK: - Declaration shape diagnostics

/// The error for `@Event @JS var`, attached to `@JS` and carrying a fix-it that removes it. An event
/// is exposed to JavaScript through `addListener`, so `@JS` has nothing to add. Removing it also
/// removes the error `@JS` reports for a property with a closure type.
private func jsAttributeDiagnostic(for attribute: AttributeSyntax) -> DiagnosticsError {
  let fixIt = FixIt(
    message: EventFixItMessage("Remove '@JS'", id: "event-remove-js"),
    changes: removalChanges(of: attribute)
  )
  let message = EventDiagnosticMessage(
    "@Event and @JS can't be combined on the same property: an event is exposed to JavaScript on its own. Remove @JS",
    id: "event-with-js"
  )
  return DiagnosticsError(diagnostics: [Diagnostic(node: attribute, message: message, fixIts: [fixIt])])
}

/// The error for `@Event static var` or `@Event class var`, attached to the modifier and carrying a
/// fix-it that removes it.
private func typeLevelModifierDiagnostic(for modifier: DeclModifierSyntax) -> DiagnosticsError {
  let keyword = modifier.name.text
  let fixIt = FixIt(
    message: EventFixItMessage("Remove '\(keyword)'", id: "event-remove-type-level-modifier"),
    changes: removalChanges(of: modifier)
  )
  let message = EventDiagnosticMessage(
    "@Event must be an instance property: events are emitted from a module or shared object instance. Remove '\(keyword)'",
    id: "event-type-level"
  )
  return DiagnosticsError(diagnostics: [Diagnostic(node: modifier, message: message, fixIts: [fixIt])])
}

/// The error for an `@Event` property with an initial value, attached to the initializer. When the
/// property declares its type, a fix-it removes the initial value; without the type, the property
/// would be left with no type at all.
private func initialValueDiagnostic(
  for initializer: InitializerClauseSyntax,
  in binding: PatternBindingSyntax,
  of varDecl: VariableDeclSyntax
) -> DiagnosticsError {
  let message = EventDiagnosticMessage(
    "@Event property can't have an initial value: the macro synthesizes the closure. Remove the initial value",
    id: "event-initial-value"
  )
  guard binding.typeAnnotation != nil else {
    return DiagnosticsError(diagnostics: [Diagnostic(node: initializer, message: message)])
  }
  // The type before the initializer takes over the trailing trivia of the initializer, so the space
  // before `=` doesn't stay behind.
  var newBinding = binding.with(\.initializer, nil)
  newBinding.typeAnnotation?.trailingTrivia = initializer.trailingTrivia
  let fixIt = FixIt(
    message: EventFixItMessage("Remove the initial value", id: "event-remove-initial-value"),
    changes: [
      .replace(
        oldNode: Syntax(varDecl),
        newNode: Syntax(varDecl.with(\.bindings, PatternBindingListSyntax([newBinding])))
      )
    ]
  )
  return DiagnosticsError(diagnostics: [Diagnostic(node: initializer, message: message, fixIts: [fixIt])])
}

/// The error for an `@Event` function type that doesn't return `Void`, attached to the return type
/// and carrying a fix-it that replaces it with `Void`.
private func returnTypeDiagnostic(for returnType: TypeSyntax) -> DiagnosticsError {
  let voidType = TypeSyntax(IdentifierTypeSyntax(name: .identifier("Void")))
    .with(\.leadingTrivia, returnType.leadingTrivia)
    .with(\.trailingTrivia, returnType.trailingTrivia)
  let fixIt = FixIt(
    message: EventFixItMessage("Replace '\(returnType.trimmedDescription)' with 'Void'", id: "event-return-void"),
    changes: [.replace(oldNode: Syntax(returnType), newNode: Syntax(voidType))]
  )
  let message = EventDiagnosticMessage(
    "@Event function type must return 'Void': an event dispatches to JavaScript and has no return value",
    id: "event-non-void-return"
  )
  return DiagnosticsError(diagnostics: [Diagnostic(node: returnType, message: message, fixIts: [fixIt])])
}

private struct EventDiagnosticMessage: DiagnosticMessage {
  let message: String
  let diagnosticID: MessageID
  let severity: DiagnosticSeverity = .error

  init(_ message: String, id: String) {
    self.message = message
    self.diagnosticID = MessageID(domain: "ExpoModulesMacros", id: id)
  }
}

private struct EventFixItMessage: FixItMessage {
  let message: String
  let fixItID: MessageID

  init(_ message: String, id: String) {
    self.message = message
    self.fixItID = MessageID(domain: "ExpoModulesMacros", id: id)
  }
}

// MARK: - Declaration shape helpers

/// The spelled name of the innermost type declaration enclosing the macro, read from the lexical
/// context, so the emitter assertion can name the user's type in the conformance diagnostic
/// ("requires that 'MyModule' conform to 'EventEmitter'" instead of "'Self'"). Returns `nil` (the
/// caller falls back to `Self`) when there's no enclosing type, or when it's a generic type
/// declaration: `Foo.self` isn't valid for an unbound generic, while `Self` works anywhere. An
/// extension can't be detected as generic syntactically (see the extension case below).
private func enclosingTypeName(in context: some MacroExpansionContext) -> String? {
  for scope in context.lexicalContext {
    if let classDecl = scope.as(ClassDeclSyntax.self) {
      return classDecl.genericParameterClause == nil ? classDecl.name.text : nil
    }
    if let structDecl = scope.as(StructDeclSyntax.self) {
      return structDecl.genericParameterClause == nil ? structDecl.name.text : nil
    }
    if let actorDecl = scope.as(ActorDeclSyntax.self) {
      return actorDecl.genericParameterClause == nil ? actorDecl.name.text : nil
    }
    if let extensionDecl = scope.as(ExtensionDeclSyntax.self) {
      // An extension carries no generic-parameter clause of its own, so a bare extended type
      // (`extension Box`) is indistinguishable from a non-generic one (`extension Foo`); both read
      // as a plain identifier here. A written bound form (`extension Box<Int>`) is valid as `.self`,
      // and the common non-generic case keeps its spelled name in the diagnostic. The unguarded gap
      // is `extension <Generic>` with the parameters omitted, where the spelled name is an unbound
      // generic invalid as `.self`; events on generic types in an extension are rare enough that the
      // resulting compile error is an acceptable price for naming the user's type everywhere else.
      return extensionDecl.extendedType.trimmedDescription
    }
  }
  return nil
}

private func isTypeLevelModifier(_ modifier: DeclModifierSyntax) -> Bool {
  return modifier.name.tokenKind == .keyword(.static) || modifier.name.tokenKind == .keyword(.class)
}

/// The function type underlying a property's type annotation, unwrapping attributes
/// (`@Sendable (P) -> Void`) and single-element parentheses (`((P) -> Void)`). Returns `nil` when
/// the annotation is missing or isn't a function type, including an optional function type:
/// an event is always present, never `nil`.
private func underlyingFunctionType(of type: TypeSyntax?) -> FunctionTypeSyntax? {
  guard let type else {
    return nil
  }
  if let attributed = type.as(AttributedTypeSyntax.self) {
    return underlyingFunctionType(of: attributed.baseType)
  }
  if let tuple = type.as(TupleTypeSyntax.self),
    tuple.elements.count == 1, let element = tuple.elements.first, element.firstName == nil
  {
    return underlyingFunctionType(of: element.type)
  }
  return type.as(FunctionTypeSyntax.self)
}

/// True when the function type's return is written as `Void` / `()`. Function types always carry an
/// explicit return clause, so unlike a function declaration there's no "absent" case. A module-qualified
/// `Swift.Void` and redundant parentheses (`(Void)`, `(())`) are accepted too, so a valid void return
/// written one of those ways isn't rejected with a misleading "must return 'Void'" diagnostic.
private func isVoidReturn(_ type: TypeSyntax) -> Bool {
  // Peel single-element, unlabeled parentheses: `(Void)` and `(())` are the same type as their content.
  if let tuple = type.as(TupleTypeSyntax.self), tuple.elements.count == 1,
    let element = tuple.elements.first, element.firstName == nil
  {
    return isVoidReturn(element.type)
  }
  let text = type.trimmedDescription
  return text == "Void" || text == "()" || text == "Swift.Void"
}
