import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros

/// Member macro applied to a `SharedObject` subclass, direct or not (a `SharedRef<T>` subclass too).
/// Scans the class body for declarations marked with `@JS` and binds them directly through overrides of
/// the `SharedObject` hooks core calls when it builds the JavaScript class. The class's JavaScript name
/// is emitted as a `_jsName` override, and its place in the JavaScript class chain as `_jsClassType` and
/// `_jsSuperclassType` overrides.
///
///   @SharedObject
///   public final class Cache: SharedObject {
///     @JS
///     init(name: String) { self.name = name }
///
///     @JS
///     func get(_ key: String) -> String? { ... }
///
///     @JS
///     var size: Int { 42 }
///   }
///
/// The companion `@ExpoModule(classes: [Cache.self])` registers the class with the module, which
/// exposes it in its JavaScript object.
///
/// As an extension macro, it adds an `AnySharedObject` conformance when the class doesn't conform
/// yet, and an `@unchecked Sendable` conformance when the class isn't `Sendable` yet.
public struct SharedObjectMacro: MemberMacro {
  public static func expansion(
    of node: AttributeSyntax,
    providingMembersOf declaration: some DeclGroupSyntax,
    conformingTo protocols: [TypeSyntax],
    in context: some MacroExpansionContext
  ) throws -> [DeclSyntax] {
    guard let classDecl = declaration.as(ClassDeclSyntax.self) else {
      throw MacroExpansionErrorMessage("@SharedObject can only be applied to a class")
    }
    diagnoseNonPublicClass(
      classDecl,
      macroName: "@SharedObject",
      reason: "export it",
      idPrefix: "sharedobject",
      in: context
    )

    // A class without an inheritance clause has no superclass, so it can't be a `SharedObject`. Any
    // other superclass isn't checked: the macro sees only this declaration, so it can't tell an
    // indirect subclass (`class Thumbnail: ImageRef`) from an unrelated class. The compiler reports a
    // class that isn't a `SharedObject` subclass on the `_jsName` override, which is always emitted.
    if classDecl.inheritanceClause == nil {
      throw DiagnosticsError(diagnostics: [missingBaseClassDiagnostic(for: classDecl)])
    }
    let typeName = classDecl.name.text
    let jsName = jsNameArgument(of: node) ?? withoutBackticks(typeName)

    // A superclass other than `SharedObject` or `SharedRef` may be another `@SharedObject` class, whose
    // JavaScript class is up the prototype chain of this class's prototype and constructor (see
    // `_jsSuperclassType` below). An assignment to a name that it binds as an accessor would call the
    // accessor, so each function of this class defines its name as a data property first.
    let mayInheritJSMembers = !inheritsFromAny(classDecl, names: ["SharedObject", "SharedRef"])
    let isFinal = classDecl.modifiers.contains { $0.name.tokenKind == .keyword(.final) }
    // The hooks of an `open` class are `open`, so that a subclass in another module can override them.
    let access = classDecl.modifiers.contains { $0.name.tokenKind == .keyword(.open) } ? "open" : "public"

    // `@JS func`s/`var`s and the `@JS init` are bound directly into the shared object's JS object by
    // the synthesized `_decorateSharedObject(prototype:)` / `_decorateSharedObject(constructor:)` / `_constructSharedObject`.
    //
    // Members split by the `static`/`class` modifier onto two different JS objects: instance members
    // decorate the prototype (receiver recovered from JS `this`), static members decorate the
    // constructor (called on the metatype). A JS instance and static member may share a name without
    // colliding: they live on different objects.
    var instanceFunctions: [JSFunction] = []
    var instanceProperties: [JSProperty] = []
    var staticFunctions: [JSFunction] = []
    var staticProperties: [JSProperty] = []
    var constructor: JSConstructor?
    var assertions: [MemberConformanceAssertion] = []
    let aliases = TupleTypeAliases(in: classDecl.memberBlock)

    for member in classDecl.memberBlock.members {
      // The types of a `@JS` member are read with the class's tuple aliases resolved.
      let decl = aliases.resolving(member.decl)
      // A generic member is reported by `@JS` and left out, so the build has no errors in its binding.
      if memberHasJSAttribute(decl) && jsGenericParameterClause(of: decl) != nil {
        continue
      }
      if memberHasJSAttribute(decl), let assertion = jsConformanceAssertionBody(for: decl) {
        assertions.append(assertion)
      }

      if let initDecl = decl.as(InitializerDeclSyntax.self),
        initDecl.attributes.firstAttribute(named: "JS") != nil
      {
        if constructor != nil {
          throw MacroExpansionErrorMessage(
            "@SharedObject classes can have at most one @JS initializer: JavaScript classes have a single constructor"
          )
        }
        constructor = JSConstructor(initDecl: initDecl)
        continue
      }

      if let funcDecl = decl.as(FunctionDeclSyntax.self),
        let attribute = funcDecl.attributes.firstAttribute(named: "JS")
      {
        let function = JSFunction(funcDecl: funcDecl, attribute: attribute)
        let bound = [function] + (function.asyncVariant.map { [$0] } ?? [])
        if isTypeLevel(funcDecl.modifiers) {
          staticFunctions.append(contentsOf: bound)
        } else {
          instanceFunctions.append(contentsOf: bound)
        }
        continue
      }

      if let varDecl = decl.as(VariableDeclSyntax.self),
        let attribute = varDecl.attributes.firstAttribute(named: "JS")
      {
        let collected = collectProperties(varDecl: varDecl, attribute: attribute)
        if isTypeLevel(varDecl.modifiers) {
          staticProperties.append(contentsOf: collected)
        } else {
          instanceProperties.append(contentsOf: collected)
        }
      }
    }

    diagnoseJSNameCollisions(functions: instanceFunctions, properties: instanceProperties, in: context)
    diagnoseJSNameCollisions(functions: staticFunctions, properties: staticProperties, in: context)
    diagnoseReservedJSNames(
      functions: instanceFunctions,
      properties: instanceProperties,
      on: .prototype,
      in: context
    )
    diagnoseReservedJSNames(
      functions: staticFunctions,
      properties: staticProperties,
      on: .constructor,
      in: context
    )
    diagnoseEventNameCollisions(in: classDecl.memberBlock, in: context)

    // The resolved JS class name, read by core when it builds the class. An `override` of the
    // `SharedObject` class property, so core reads it through the concrete type's metatype.
    //
    // `_jsClassType` returns this class, written by name and not as `Self`, so a subclass without the
    // macro inherits it and core gives that subclass the JavaScript class of this one. Inside a generic
    // class, the bare name means the class with its own generic arguments. `_jsSuperclassType` returns the
    // `_jsClassType` of the superclass, which is the nearest class above with the macro, or `nil` for the
    // base `SharedObject` or `SharedRef`. Core builds the JavaScript class of that class first and
    // creates this one on it, so the JavaScript chain follows the Swift chain.
    var emitted: [DeclSyntax] = [
      "\(raw: access) override class var _jsName: String { \"\(raw: jsName)\" }",
      "\(raw: access) override class var _jsClassType: (any AnySharedObject.Type)? { \(raw: typeName).self }",
      "\(raw: access) override class var _jsSuperclassType: (any AnySharedObject.Type)? { super._jsClassType }",
    ]

    // Direct JSI binding, split by which JS object each member decorates:
    // `_decorateSharedObject(prototype:)` binds instance `@JS func`/`var`s (unwrapping the per-call receiver from
    // `this`); `_decorateSharedObject(constructor:)` binds `static`/`class` ones (called on the metatype); and
    // `_constructSharedObject` builds an instance from the `@JS init` arguments. Both decorator phases
    // are emitted also when they bind nothing, since a class without its own phase would run the phase of
    // its superclass on its own objects. Each class binds only its own members: the inherited ones are on
    // the JavaScript class of the superclass. The constructor is emitted only for a `@JS init`.
    emitted.append(
      buildDecorateSharedObjectPhase(
        phase: .prototype,
        functions: instanceFunctions,
        properties: instanceProperties,
        typeName: typeName,
        access: access,
        replacesInherited: mayInheritJSMembers
      )
    )
    emitted.append(
      buildDecorateSharedObjectPhase(
        phase: .constructor,
        functions: staticFunctions,
        properties: staticProperties,
        typeName: typeName,
        access: access,
        replacesInherited: mayInheritJSMembers
      )
    )
    if let constructor {
      emitted.append(constructor.buildConstructor(typeName: typeName, access: access, isFinal: isFinal))
    }

    // The conformance assertions of the `@JS` members, which `@JS` leaves to this macro (see
    // `jsConformanceAssertionBody`).
    if let assertion = classConformanceAssertions(assertions) {
      emitted.append(assertion)
    }

    return emitted
  }
}

extension SharedObjectMacro: MemberAttributeMacro {
  public static func expansion(
    of node: AttributeSyntax,
    attachedTo declaration: some DeclGroupSyntax,
    providingAttributesFor member: some DeclSyntaxProtocol,
    in context: some MacroExpansionContext
  ) throws -> [AttributeSyntax] {
    guard memberHasJSAttribute(member) else {
      return []
    }
    // `@JS(.concurrent)` opts the member out of the JS-thread stamp and onto the concurrent pool.
    if isConcurrentJSMember(member) {
      return ["@concurrent"]
    }
    guard shouldStampJavaScriptActor(on: member, enclosedBy: declaration) else {
      return []
    }
    return ["@JavaScriptActor"]
  }
}

extension SharedObjectMacro: ExtensionMacro {
  public static func expansion(
    of node: AttributeSyntax,
    attachedTo declaration: some DeclGroupSyntax,
    providingExtensionsOf type: some TypeSyntaxProtocol,
    conformingTo protocols: [TypeSyntax],
    in context: some MacroExpansionContext
  ) throws -> [ExtensionDeclSyntax] {
    var extensions: [ExtensionDeclSyntax] = []
    if let conformance = anySharedObjectExtension(for: type, of: declaration, conformingTo: protocols) {
      extensions.append(conformance)
    }
    if let sendable = uncheckedSendableExtension(for: type, of: declaration, conformingTo: protocols) {
      extensions.append(sendable)
    }
    return extensions
  }
}

/// The `AnySharedObject` conformance that `@SharedObject` adds to its class, or `nil` when the class
/// already conforms. The compiler leaves `AnySharedObject` out of `protocols` when the class conforms,
/// also through a superclass, as every subclass of `SharedObject` does. The inheritance clause is
/// checked too, so that `expand`, which passes every declared conformance, gives the same result for a
/// class that names `SharedObject`, `SharedRef` or `AnySharedObject`, also as
/// `nonisolated AnySharedObject`. `expand` can't see that an indirect subclass
/// (`class Thumbnail: ImageRef`) conforms, so it reports the conformance for it.
///
/// The extension is empty. Only a class that has no `SharedObject` superclass gets it, and the macro
/// emits the hooks of every class as overrides of `SharedObject` members, so such a class doesn't
/// compile. The conformance is `nonisolated`, so core can use it on any thread also when the module
/// builds with `-default-isolation MainActor`.
private func anySharedObjectExtension(
  for type: some TypeSyntaxProtocol,
  of declaration: some DeclGroupSyntax,
  conformingTo protocols: [TypeSyntax]
) -> ExtensionDeclSyntax? {
  guard protocols.contains(where: { $0.trimmedDescription == "AnySharedObject" }),
    let classDecl = declaration.as(ClassDeclSyntax.self),
    !inheritsFromAny(classDecl, names: ["SharedObject", "SharedRef"]),
    !inheritsProtocol(named: "AnySharedObject", in: classDecl)
  else {
    return nil
  }
  let conformance: DeclSyntax = "extension \(type.trimmed): nonisolated AnySharedObject {}"
  return conformance.cast(ExtensionDeclSyntax.self)
}

/// The error for a `@SharedObject` class without an inheritance clause, with a fix-it that makes it
/// inherit from `SharedObject`: `class Cache {` becomes `class Cache: SharedObject {`.
private func missingBaseClassDiagnostic(for classDecl: ClassDeclSyntax) -> Diagnostic {
  // The name carries the space before `{` as trailing trivia, so move it onto the clause to keep the
  // spacing.
  let name = classDecl.name
  let clause = InheritanceClauseSyntax(
    colon: .colonToken(trailingTrivia: .space),
    inheritedTypes: InheritedTypeListSyntax([
      InheritedTypeSyntax(type: TypeSyntax(IdentifierTypeSyntax(name: .identifier("SharedObject"))))
    ])
  )
  let fixIt = FixIt(
    message: SharedObjectFixItMessage("Inherit from 'SharedObject'", id: "sharedobject-add-base-class"),
    changes: [
      .replace(
        oldNode: Syntax(classDecl),
        newNode: Syntax(
          classDecl
            .with(\.name, name.with(\.trailingTrivia, []))
            .with(\.inheritanceClause, clause.with(\.trailingTrivia, name.trailingTrivia))
        )
      )
    ]
  )
  return Diagnostic(
    node: name,
    message: SharedObjectDiagnosticMessage(
      "@SharedObject class '\(name.text)' must inherit from 'SharedObject', directly or through another class such as 'SharedRef'. Add ': SharedObject' to the class declaration",
      id: "sharedobject-missing-base-class"
    ),
    fixIts: [fixIt]
  )
}

private struct SharedObjectDiagnosticMessage: 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 SharedObjectFixItMessage: FixItMessage {
  let message: String
  let fixItID: MessageID

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