import Foundation
import XCTest
import AgentDeviceSnapshotPresentation

enum RunnerCommandLifecycleState: String {
  case notAccepted
  case accepted
  case started
  case completed
  case failed
}

extension RunnerCommandLifecycleState {


  var isTerminal: Bool {
    self == .completed || self == .failed
  }
}

struct RunnerCommandJournalEntry {
  let commandId: String
  let command: String
  var state: RunnerCommandLifecycleState
  var responseOk: Bool?
  var responseJson: String?
  var error: ErrorPayload?




  var dispatched = false

  let executionToken: Int
  let isReadOnly: Bool
}


enum RunnerCommandAdmission {


  case execute(executionToken: Int)



  case join(executionToken: Int)

  case terminal(outcome: Response)
}





final class RunnerCommandJournal {
  private let lock = NSLock()
  private let maxEntries = 64



  static let closedCommandIdSafetyValve = 4096
  private let maxResponseJsonBytes = 16 * 1024
  private var entries: [String: RunnerCommandJournalEntry] = [:]
  private var order: [String] = []





  private var closedCommandIds: Set<String> = []
  private var closedOrder: [String] = []


  private var nextExecutionToken = 0








  @discardableResult
  func accept(
    command: Command,
    registeringJoin register: (Int) -> Void = { _ in }
  ) -> RunnerCommandAdmission {
    lock.lock()
    defer { lock.unlock() }
    guard let commandId = command.commandId?.trimmedNonEmpty else {

      return .execute(executionToken: mintExecutionToken())
    }
    guard let entry = entries[commandId] else {



      if closedCommandIds.contains(commandId) {


        return .terminal(
          outcome: alreadyFinishedRefusal(command: command, commandId: commandId, outcomeDropped: true)
        )
      }
      return claim(command: command, commandId: commandId)
    }
    if !entry.state.isTerminal {
      let executionToken = entry.executionToken
      register(executionToken)
      return .join(executionToken: executionToken)
    }



    guard entry.dispatched, !entry.isReadOnly else {
      return claim(command: command, commandId: commandId)
    }
    return .terminal(outcome: recordedOutcome(for: entry))
  }


  private func mintExecutionToken() -> Int {
    nextExecutionToken += 1
    return nextExecutionToken
  }

  func start(command: Command) {
    transition(command: command, reorders: true) { entry in
      entry.state = .started
    }
  }




  func finish(command: Command, response: Response) {
    transition(command: command, reorders: true) { entry in
      entry.state = response.ok ? .completed : .failed
      entry.responseOk = response.ok
      entry.responseJson = encodeResponseJson(command: command, response: response)
      entry.error = response.error
    }
  }






  func fail(command: Command, error: Error) {
    let payload = RunnerTests.thrownErrorPayload(for: error)
    transition(command: command, reorders: true) { entry in
      entry.state = .failed
      entry.error = payload
    }
  }

  func status(normalizedCommandId commandId: String) -> DataPayload {
    lock.lock()
    let entry = entries[commandId]
    lock.unlock()
    guard let entry else {
      return DataPayload(
        commandId: commandId,
        lifecycleState: RunnerCommandLifecycleState.notAccepted.rawValue
      )
    }
    return DataPayload(
      commandId: entry.commandId,
      lifecycleState: entry.state.rawValue,
      lifecycleCommand: entry.command,
      lifecycleResponseOk: entry.responseOk,
      lifecycleResponseJson: entry.responseJson,
      lifecycleErrorCode: entry.error?.code,
      lifecycleErrorMessage: entry.error?.message,
      lifecycleErrorHint: entry.error?.hint
    )
  }


  private func claim(command: Command, commandId: String) -> RunnerCommandAdmission {
    let executionToken = mintExecutionToken()
    entries[commandId] = RunnerCommandJournalEntry(
      commandId: commandId,
      command: command.command.rawValue,
      state: .accepted,
      responseOk: nil,
      responseJson: nil,
      error: nil,
      executionToken: executionToken,
      isReadOnly: command.traits.isReadOnly
    )
    order.removeAll { $0 == commandId }
    order.append(commandId)
    pruneIfNeeded()
    return .execute(executionToken: executionToken)
  }





  func markDispatched(command: Command) {
    transition(command: command, reorders: false) { entry in
      entry.dispatched = true
    }
  }







  private func transition(
    command: Command,
    reorders: Bool,
    _ mutate: (inout RunnerCommandJournalEntry) -> Void
  ) {
    guard let commandId = command.commandId?.trimmedNonEmpty else { return }
    lock.lock()
    defer { lock.unlock() }
    guard var entry = entries[commandId], !entry.state.isTerminal else { return }
    mutate(&entry)
    entries[commandId] = entry
    guard reorders else { return }
    order.removeAll { $0 == commandId }
    order.append(commandId)
    pruneIfNeeded()
  }






  private func pruneIfNeeded() {
    while order.count > maxEntries {
      guard let removable = order.first(where: { entries[$0]?.state.isTerminal == true }) else {
        return
      }
      order.removeAll { $0 == removable }


      if let entry = entries[removable], entry.dispatched, !entry.isReadOnly {
        closedCommandIds.insert(removable)
        closedOrder.append(removable)
        while closedOrder.count > Self.closedCommandIdSafetyValve {



          closedCommandIds.remove(closedOrder.removeFirst())
        }
      }
      entries.removeValue(forKey: removable)
    }
  }



  private func recordedOutcome(for entry: RunnerCommandJournalEntry) -> Response {
    if let responseJson = entry.responseJson,
      let recorded = try? JSONDecoder().decode(Response.self, from: Data(responseJson.utf8))
    {
      return recorded
    }
    if let error = entry.error {
      return Response(ok: false, error: error)
    }
    return alreadyFinishedRefusal(
      commandId: entry.commandId,
      commandName: entry.command,
      outcomeDropped: false
    )
  }

  private func alreadyFinishedRefusal(
    command: Command,
    commandId: String,
    outcomeDropped: Bool
  ) -> Response {
    alreadyFinishedRefusal(
      commandId: commandId,
      commandName: command.command.rawValue,
      outcomeDropped: outcomeDropped
    )
  }

  private func alreadyFinishedRefusal(
    commandId: String,
    commandName: String,
    outcomeDropped: Bool
  ) -> Response {
    let reason =
      outcomeDropped
      ? "The runner already finished \(commandName) with id \(commandId). That command's recorded outcome has since been dropped from the journal, so there is no response to replay."
      : "The runner already finished \(commandName) with id \(commandId) and kept no response to replay."
    return Response(
      ok: false,
      error: ErrorPayload(
        code: RunnerTests.RunnerWireErrorCode.commandAlreadyFinished,
        message: reason,
        hint:
          "Read the screen with snapshot before sending anything else: the finished command's work reached the device, so it may already have had its effect."
      )
    )
  }

  private func encodeResponseJson(command: Command, response: Response) -> String? {
    guard command.traits.retainsJournalResponseJson else { return nil }
    guard let data = try? JSONEncoder().encode(response) else { return nil }
    guard data.count <= maxResponseJsonBytes else { return nil }
    return String(data: data, encoding: .utf8)
  }
}
