import XCTest
import AgentDeviceSnapshotPresentation



struct LitPanelBookingKey: Equatable {
  let bundleID: String
  let requestID: UUID
}

struct LitPanelSurface {
  let key: LitPanelBookingKey
  let displayID: UInt
  let window: XCUIElement
  let geometry: SurfaceGeometry
}


final class RunnerLitPanelState {
  var requestID: UUID?
  var panel: RunnerLitPanel?
  var surface: LitPanelSurface?
}

extension RunnerTests {
  @discardableResult
  func setRequestLitPanel(from command: Command) -> UUID {
    let requestID = UUID()
    var panel: RunnerLitPanel?
    if let fact = command.litPanel, fact.displayId != 0, fact.widthPt.isFinite, fact.heightPt.isFinite,
      fact.widthPt > 0, fact.heightPt > 0
    {
      panel = RunnerLitPanel(displayID: fact.displayId, widthPt: fact.widthPt, heightPt: fact.heightPt)
    }
    let state = litPanelState
    let write = {
      state.requestID = requestID
      state.panel = panel
      state.surface = nil
    }
    if Thread.isMainThread {
      write()
    } else {
      DispatchQueue.main.async(execute: write)
    }
    return requestID
  }

  func endRequestLitPanel(_ requestID: UUID) {
    let state = litPanelState
    let clear = {
      guard state.requestID == requestID else { return }
      state.requestID = nil
      state.panel = nil
      state.surface = nil
    }
    if Thread.isMainThread {
      clear()
    } else {
      DispatchQueue.main.async(execute: clear)
    }
  }


  var requestLitPanel: RunnerLitPanel? { litPanelState.panel }


  func bookRequestLitPanelSurface(app: XCUIApplication) -> RunnerAppScreenCaptureFailure? {
    guard let litPanel = requestLitPanel else { return nil }
    guard let requestID = litPanelState.requestID,
      let bundleID = safely("LIT_PANEL_APP_IDENTITY", { app.value(forKey: "bundleID") as? String })?.trimmedNonEmpty
    else { return .unresolvedScreen }
    let key = LitPanelBookingKey(bundleID: bundleID, requestID: requestID)
    if litPanelState.surface?.key == key { return nil }
    litPanelState.surface = nil
    var window: AnyObject?
    var frame = CGRect.null
    var screen: AnyObject?
    let failure = RunnerResolveLitPanelWindow(app, litPanel, &window, &frame, &screen)
    guard failure == .none, let element = window as? XCUIElement else {
      return RunnerAppScreenCaptureFailure(failure == .none ? .unresolvedWindow : failure)
    }
    litPanelState.surface = LitPanelSurface(key: key, displayID: litPanel.displayID, window: element, geometry: surfaceGeometry(windowFrame: frame, app: app))
    return nil
  }

  func requireRequestLitPanelSurface(app: XCUIApplication) throws -> LitPanelSurface {
    if let refusal = bookRequestLitPanelSurface(app: app) { throw refusal }
    guard let surface = litPanelState.surface else {
      throw RunnerAppScreenCaptureFailure.unresolvedScreen
    }
    return surface
  }



  func elementSearchRoots(root: XCUIElement, litDisplayID: UInt?) throws -> [XCUIElement] {
    guard let litDisplayID else { return [root] }
    var windows: [XCUIElement]?
    let walk = holdingRecordedIssues {
      windows = RunnerCopyLitPanelWindows(root, litDisplayID)?.compactMap { $0 as? XCUIElement }





    }
    guard walk.issues.isEmpty, walk.exceptionMessage == nil, let windows, !windows.isEmpty else {
      for issue in walk.issues {
        NSLog("AGENT_DEVICE_RUNNER_LIT_PANEL_WALK_ISSUE=%@", issue.compactDescription)
      }
      NSLog(
        "AGENT_DEVICE_RUNNER_LIT_PANEL_WALK_REFUSED issues=%ld exception=%@ windows=%ld",
        walk.issues.count, walk.exceptionMessage ?? "none", windows?.count ?? -1
      )
      throw RunnerAppScreenCaptureFailure.unresolvedScreen
    }
    return windows
  }


  func elementQueries(app: XCUIApplication, matching types: XCUIElement.ElementType...) throws -> [XCUIElementQuery] {
    queries(matching: types, in: try elementSearchRoots(root: app, litDisplayID: requestLitPanel?.displayID))
  }

  func elementQueries(
    root: XCUIElement,
    matching types: XCUIElement.ElementType...,
    litDisplayID: UInt?
  ) throws -> [XCUIElementQuery] {
    queries(matching: types, in: try elementSearchRoots(root: root, litDisplayID: litDisplayID))
  }

  private func queries(
    matching types: [XCUIElement.ElementType],
    in roots: [XCUIElement]
  ) -> [XCUIElementQuery] {
    types.flatMap { type in roots.map { $0.descendants(matching: type) } }
  }
}
