import XCTest
import Network

extension RunnerTests {




  static let requestTimeout: TimeInterval = 30


  static let connectionIdleTimeout: TimeInterval = 30


  func handle(connection: NWConnection) {
    guard let token = listenerToken else {
      connection.cancel()
      return
    }
    transportConnections[ObjectIdentifier(connection)] = connection
    connection.stateUpdateHandler = { [weak self] state in
      switch state {
      case .ready:
        self?.admit(connection, token: token)
      case .failed:
        connection.cancel()
      case .cancelled:
        connection.stateUpdateHandler = nil
        self?.transportConnections.removeValue(forKey: ObjectIdentifier(connection))
      default:
        break
      }
    }
    connection.start(queue: transportQueue)
  }

  private func admit(_ connection: NWConnection, token: RunnerListenerToken) {
    let peer = RunnerListenerPeer.of(connection)
    guard peer.isAdmitted(acceptsForwardedConnections: acceptsForwardedConnections) else {
      connection.cancel()
      return
    }
    let inbound = RunnerInboundRequest(token: token)
    if peer != .loopback {
      armDeadline(for: inbound, over: connection)
    }
    receiveRequest(inbound, over: connection)
  }



  private func receiveRequest(_ inbound: RunnerInboundRequest, over connection: NWConnection) {
    connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) {
      [weak self] data, _, isComplete, error in
      guard let self, !inbound.closed else { return }
      if let data, !data.isEmpty {
        self.consume(data, for: inbound, over: connection)
      } else if error != nil || isComplete {
        inbound.close()
        connection.cancel()
      } else {
        self.receiveRequest(inbound, over: connection)
      }
    }
  }

  private func consume(_ data: Data, for inbound: RunnerInboundRequest, over connection: NWConnection) {
    inbound.idleDeadline?.cancel()
    inbound.idleDeadline = nil
    if inbound.deadline == nil {
      armDeadline(for: inbound, over: connection)
    }
    let alreadyScanned = inbound.buffer.count
    inbound.buffer.append(data)
    if inbound.head == nil {
      switch RunnerHttpRequestFraming.admitHead(
        inbound.buffer,
        token: inbound.token,
        alreadyScanned: alreadyScanned
      ) {
      case .incomplete:
        receiveRequest(inbound, over: connection)
        return
      case .rejected(let rejection):
        reject(inbound, with: rejection, over: connection)
        return
      case .admitted(let head):
        inbound.head = head
      }
    }
    guard let head = inbound.head else { return }
    let bodyEnd = head.bodyOffset + head.contentLength
    guard inbound.buffer.count >= bodyEnd else {
      receiveRequest(inbound, over: connection)
      return
    }



    inbound.close()
    let body = inbound.buffer.subdata(in: head.bodyOffset..<bodyEnd)
    let remainder = Data(inbound.buffer.suffix(from: bodyEnd))
    handleRequestBody(body) { [weak self, token = inbound.token] result in
      self?.sendResult(result, over: connection, request: head, token: token, remainder: remainder)
    }
  }

  private func armDeadline(for inbound: RunnerInboundRequest, over connection: NWConnection) {
    let deadline = DispatchWorkItem { [weak self, inbound] in
      guard let self, !inbound.closed else { return }
      self.reject(inbound, with: .timedOut, over: connection)
    }
    inbound.deadline = deadline
    transportQueue.asyncAfter(deadline: .now() + Self.requestTimeout, execute: deadline)
  }

  private func reject(
    _ inbound: RunnerInboundRequest,
    with rejection: RunnerHttpRequestRejection,
    over connection: NWConnection
  ) {
    inbound.close()
    NSLog("AGENT_DEVICE_RUNNER_REQUEST_REJECTED status=%d", rejection.status)
    let response = jsonResponse(
      status: rejection.status,
      response: errorResponse(code: rejection.code, message: rejection.message)
    )
    sendResponse(response, over: connection, closeConnection: true)
  }

  private func sendResult(
    _ result: (response: RunnerHttpResponse, shouldFinish: Bool),
    over connection: NWConnection,
    request: RunnerHttpAdmittedHead,
    token: RunnerListenerToken,
    remainder: Data
  ) {
    let closeConnection = !request.keepsConnectionAlive || result.shouldFinish
    if result.shouldFinish { shutdownResponseWrites.enter() }
    sendResponse(result.response, over: connection, closeConnection: closeConnection) { [weak self] sent in
      guard let self else { return }
      if result.shouldFinish {
        self.shutdownResponseWrites.leave()
      } else if sent && !closeConnection {
        self.readNextRequest(over: connection, token: token, buffered: remainder)
      }
    }
  }

  private func readNextRequest(over connection: NWConnection, token: RunnerListenerToken, buffered: Data) {
    guard transportConnections[ObjectIdentifier(connection)] != nil else { return }
    let inbound = RunnerInboundRequest(token: token)
    if !buffered.isEmpty {
      consume(buffered, for: inbound, over: connection)
      return
    }

    let idleDeadline = DispatchWorkItem {
      guard !inbound.closed else { return }
      inbound.close()
      connection.cancel()
    }
    inbound.idleDeadline = idleDeadline
    transportQueue.asyncAfter(deadline: .now() + Self.connectionIdleTimeout, execute: idleDeadline)
    receiveRequest(inbound, over: connection)
  }

  private func sendResponse(
    _ response: RunnerHttpResponse,
    over connection: NWConnection,
    closeConnection: Bool,
    afterSend: @escaping @Sendable (Bool) -> Void = { _ in }
  ) {

    connection.send(content: response.encoded(closeConnection: closeConnection), completion: .contentProcessed { error in
      if let error {
        NSLog("AGENT_DEVICE_RUNNER_SEND_FAILED=%@", String(describing: error))
      }
      if closeConnection || error != nil { connection.cancel() }
      afterSend(error == nil)
    })
  }

  private func handleRequestBody(
    _ body: Data,
    completion: @escaping @Sendable ((response: RunnerHttpResponse, shouldFinish: Bool)) -> Void
  ) {
    guard String(data: body, encoding: .utf8) != nil else {
      completion((
        jsonResponse(
          status: 400,
          response: errorResponse(
            code: "INVALID_ARGS",
            message: "runner request body must be UTF-8 JSON",
            hint: "Send a JSON object matching the runner command protocol."
          )
        ),
        false
      ))
      return
    }

    do {
      let command = try JSONDecoder().decode(Command.self, from: body)
      switch offQueueRoute(for: command) {
      case .inline(let response):
        completion((jsonResponse(status: 200, response: response), false))
        return
      case .snapshotBridge:
        Self.snapshotBridgeQueue.async {
          let response = self.executeSnapshotBridge(command: command)
          self.transportQueue.async {
            completion((self.jsonResponse(status: 200, response: response), false))
          }
        }
        return
      case nil:
        break
      }






      let admission = commandJournal.accept(command: command) { [weak self] executionToken in
        self?.registerJoiner(for: executionToken, completion: completion)
      }
      switch admission {
      case .join:



        NSLog(
          "AGENT_DEVICE_RUNNER_COMMAND_COALESCED command=%@ commandId=%@",
          command.command.rawValue,
          command.commandId ?? ""
        )
      case .terminal(let outcome):

        NSLog(
          "AGENT_DEVICE_RUNNER_COMMAND_ALREADY_FINISHED command=%@ commandId=%@",
          command.command.rawValue,
          command.commandId ?? ""
        )
        completion((jsonResponse(status: 200, response: outcome), false))
      case .execute(let executionToken):
        NSLog(
          "AGENT_DEVICE_RUNNER_COMMAND_ACCEPTED command=%@ commandId=%@",
          command.command.rawValue,
          command.commandId ?? ""
        )
        enqueueAdmittedExecution(command: command) { result in
          switch result {
          case .success(let response):
            NSLog(
              "AGENT_DEVICE_RUNNER_COMMAND_COMPLETED command=%@ commandId=%@ ok=%d",
              command.command.rawValue,
              command.commandId ?? "",
              response.ok ? 1 : 0
            )
            self.deliverCommandResult(
              executionToken: executionToken,
              result: (self.jsonResponse(status: 200, response: response), command.command == .shutdown),
              completion: completion
            )
          case .failure(let error):
            NSLog(
              "AGENT_DEVICE_RUNNER_COMMAND_FAILED command=%@ commandId=%@ error=%@",
              command.command.rawValue,
              command.commandId ?? "",
              String(describing: error)
            )
            self.deliverCommandResult(
              executionToken: executionToken,
              result: (
                self.jsonResponse(status: 500, response: self.commandFailedResponse(from: error)),
                false
              ),
              completion: completion
            )
          }
        }
      }
    } catch {
      completion((
        jsonResponse(
          status: 400,
          response: errorResponse(
            code: "INVALID_ARGS",
            message: "runner command payload is invalid: \(String(describing: error))",
            hint: "Check the command name and fields against the runner protocol."
          )
        ),
        false
      ))
    }
  }





  enum OffQueueRoute {

    case inline(Response)


    case snapshotBridge
  }

  func offQueueRoute(for command: Command) -> OffQueueRoute? {
    switch command.command {
    case .status:
      return .inline(executeStatus(command: command))
    case .uptime:
      return .inline(executeUptime())
    case .snapshotBridge:
      return .snapshotBridge
    default:
      return nil
    }
  }




  func enqueueAdmittedExecution(
    command: Command,
    completion: @escaping @Sendable (Result<Response, Error>) -> Void
  ) {
    commandExecutionQueue.async {
      completion(Result { try self.executeAccepted(command: command) })
    }
  }











  func registerJoiner(
    for executionToken: Int,
    completion: @escaping @Sendable ((response: RunnerHttpResponse, shouldFinish: Bool)) -> Void
  ) {
    inFlightCommandLock.lock()
    inFlightCommandWaiters[executionToken, default: []].append(completion)
    inFlightCommandLock.unlock()
  }




  func deliverCommandResult(
    executionToken: Int,
    result: (response: RunnerHttpResponse, shouldFinish: Bool),
    completion: ((response: RunnerHttpResponse, shouldFinish: Bool)) -> Void
  ) {
    inFlightCommandLock.lock()
    let waiters = inFlightCommandWaiters.removeValue(forKey: executionToken) ?? []
    inFlightCommandLock.unlock()
    completion(result)
    for waiter in waiters {
      waiter(result)
    }

    if result.shouldFinish {
      shutdownResponseWrites.notify(queue: transportQueue) { self.finish() }
    }
  }



  private func jsonResponse(status: Int, response: Response) -> RunnerHttpResponse {





    let stamped =
      response.ok
      ? response
        .stampingCurrentUptimeMs(ProcessInfo.processInfo.systemUptime * 1000)
        .stampingCurrentMainThreadBusy(currentMainThreadBusyState().reportsMainThreadBusy)
      : response
    let encoder = JSONEncoder()
    let body = (try? encoder.encode(stamped)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
    return RunnerHttpResponse(status: status, body: body)
  }

  private func errorResponse(code: String, message: String, hint: String? = nil) -> Response {
    Response(ok: false, error: ErrorPayload(code: code, message: message, hint: hint))
  }




  func commandFailedResponse(from error: Error) -> Response {
    Response(ok: false, error: RunnerTests.thrownErrorPayload(for: error))
  }


  static let authEnforcedResponseHeader = "X-Agent-Device-Runner-Auth"

  func closeTransport() {
    listener?.cancel()
    listener = nil
    for connection in transportConnections.values { connection.cancel() }
    transportConnections.removeAll()
  }

  private func finish() {
    closeTransport()
    doneExpectation?.fulfill()
    doneExpectation = nil
  }
}


final class RunnerInboundRequest {
  let token: RunnerListenerToken
  var buffer = Data()
  var head: RunnerHttpAdmittedHead?
  var deadline: DispatchWorkItem?
  var idleDeadline: DispatchWorkItem?
  private(set) var closed = false

  init(token: RunnerListenerToken) {
    self.token = token
  }



  func close() {
    closed = true
    deadline?.cancel()
    deadline = nil
    idleDeadline?.cancel()
    idleDeadline = nil
  }
}


struct RunnerHttpResponse: Equatable, Sendable {
  let status: Int
  let body: String

  func encoded(closeConnection: Bool) -> Data {
    let headers = [
      "HTTP/1.1 \(status) \(Self.reasonPhrase(status))",
      "Content-Type: application/json",
      "Content-Length: \(body.utf8.count)",
      "\(RunnerTests.authEnforcedResponseHeader): required",
      "Connection: \(closeConnection ? "close" : "keep-alive")",
      "",
      body
    ].joined(separator: "\r\n")
    return Data(headers.utf8)
  }

  private static func reasonPhrase(_ status: Int) -> String {
    switch status {
    case 200: return "OK"
    case 400: return "Bad Request"
    case 401: return "Unauthorized"
    case 404: return "Not Found"
    case 405: return "Method Not Allowed"
    case 408: return "Request Timeout"
    case 411: return "Length Required"
    case 413: return "Content Too Large"
    case 431: return "Request Header Fields Too Large"
    default: return "Internal Server Error"
    }
  }
}
