import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  func interactiveRootNode(rect: CGRect) -> RawAXNode {
    RawAXNode(
      index: 0,
      type: "Application",
      label: nil,
      identifier: nil,
      value: nil,
      rect: SnapshotRect(rect),
      enabled: true,
      focused: nil,
      selected: nil,
      hittable: false,
      depth: 0,
      parentIndex: nil,
      hiddenContentAbove: nil,
      hiddenContentBelow: nil
    )
  }

  func interactiveRootFrame(for candidates: [RawAXNode]) -> CGRect {
    guard !candidates.isEmpty else {
      return .zero
    }
    let maxX = candidates.map { CGFloat($0.rect.x + $0.rect.width) }.max() ?? 0
    let maxY = candidates.map { CGFloat($0.rect.y + $0.rect.height) }.max() ?? 0
    return CGRect(x: 0, y: 0, width: max(1, maxX), height: max(1, maxY))
  }



  func makeSnapshotTraversalContext(
    app: XCUIApplication,
    hint: CaptureHint,
    captureDeadline: Date = .distantFuture,
    treeCaptureSliceBudgetOverride: TimeInterval? = nil,
    litPanelSurface: LitPanelSurface? = nil
  ) throws -> SnapshotTraversalContext? {
    let treeSliceBudget = treeCaptureSliceBudgetOverride ?? treeCaptureSliceBudget
    let slice = min(treeSliceBudget, max(0.5, captureDeadline.timeIntervalSinceNow))
    let rootReadStartedAt = Date()
    guard let rootSnapshot = try captureSnapshotRootBounded(app, sliceSeconds: slice) else {
      return nil
    }
    let rootReadDuration = Date().timeIntervalSince(rootReadStartedAt)





    let viewport = try runMainThreadWork(
      "snapshot_viewport",
      timeout: min(1.0, max(0.1, captureDeadline.timeIntervalSinceNow)),
      timeoutError: snapshotMainThreadTimeoutError("reading snapshot viewport")
    ) {
      try self.capturedSnapshotViewport(app: app, rootSnapshot: rootSnapshot)
    }

    let keyboardBand = captureKeyboardBandFact(snapshot: rootSnapshot, viewport: viewport, deadline: captureDeadline)

    return SnapshotTraversalContext(
      queryRoot: app,
      rootSnapshot: rootSnapshot,
      rootReadDuration: rootReadDuration,
      viewport: viewport,
      keyboardBand: keyboardBand,
      litPanelSurface: litPanelSurface
    )
  }

  static let xCTestSnapshotTimeoutCode = "IOS_TREE_CAPTURE_TIMEOUT"







  private func captureSnapshotRootBounded(
    _ element: XCUIElement,
    sliceSeconds: TimeInterval
  ) throws -> XCUIElementSnapshot? {
    if Thread.isMainThread {
      return try captureSnapshotRoot(element)
    }
    return try runMainThreadWork(
      "tree_capture",
      timeout: sliceSeconds,
      timeoutError: treeCaptureTimeoutError(sliceSeconds: sliceSeconds)
    ) {
      try self.captureSnapshotRoot(element)
    }
  }

  private func treeCaptureTimeoutError(sliceSeconds: TimeInterval) -> @Sendable () -> Error {
    {
      SnapshotCaptureFailure(
        code: Self.xCTestSnapshotTimeoutCode,
        message: "the XCTest tree capture exceeded its \(Int(sliceSeconds))s time slice",
        hint: "The capture plan will avoid or tightly bound XCTest-backed snapshot tiers on this screen."
      )
    }
  }

  func snapshotMainThreadTimeoutError(_ operation: String) -> @Sendable () -> Error {
    {
      SnapshotCaptureFailure(
        code: Self.xCTestSnapshotTimeoutCode,
        message: "timed out while \(operation) on the XCTest main thread",
        hint: "The capture plan will skip XCTest-backed snapshot tiers while the previous main-thread work drains."
      )
    }
  }

  private func captureSnapshotRoot(_ element: XCUIElement) throws -> XCUIElementSnapshot? {
    var rootSnapshot: XCUIElementSnapshot?
    var swiftErrorMessage: String?
    let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
      do {
        rootSnapshot = try element.snapshot()
      } catch {
        swiftErrorMessage = describeSnapshotError(error)
      }
    })

    if let rootSnapshot {
      return rootSnapshot
    }
    let message = exceptionMessage ?? swiftErrorMessage ?? "snapshot returned no root"
    if Self.isAxIllegalArgument(message) {
      throw axSnapshotFailure(message)
    }
    return nil
  }






  func capturedSnapshotViewport(app: XCUIApplication, rootSnapshot: XCUIElementSnapshot) throws -> SnapshotViewport {
    if requestLitPanel == nil,
      let frame = Self.fullScreenWindowFrame(
        windowFrames: rootSnapshot.children.filter { $0.elementType == .window }.map(\.frame),
        fullScreenFrame: Self.fullScreenFrame(of: app)
      )
    {
      return .reported(box: frame, interfaceOrientation: capturedInterfaceOrientation(app: app))
    }
    return try safeSnapshotViewport(app: app, readingOrientation: true)
  }






  static func fullScreenWindowFrame(windowFrames: [CGRect], fullScreenFrame: @autoclosure () -> CGRect) -> CGRect? {
    guard
      let window = windowFrames.first(where: { !$0.isEmpty }),
      Self.isFullScreenAtOrigin(window, fullScreenFrame: fullScreenFrame())
    else {
      return nil
    }
    return window
  }




  func safeSnapshotViewport(app: XCUIApplication, readingOrientation: Bool) throws -> SnapshotViewport {
    let result: Result<SnapshotViewport, Error> = safely("SNAPSHOT_VIEWPORT", .success(.missing(reason: .notProvided))) {
      Result {
        .reported(
          box: try snapshotAppFrame(app: app),
          interfaceOrientation: readingOrientation
            ? capturedInterfaceOrientation(app: app)
            : RunnerInterfaceOrientation.unknown
        )
      }
    }
    return try result.get()
  }

  private func describeSnapshotError(_ error: Error) -> String {
    let localized = error.localizedDescription
    let debug = String(describing: error)
    if localized.isEmpty { return debug }
    if debug == localized { return localized }
    return "\(localized) (\(debug))"
  }

  private func axSnapshotFailure(_ message: String) -> SnapshotCaptureFailure {
    let detail = message.trimmingCharacters(in: .whitespacesAndNewlines)
    let failureMessage: String
    if detail.isEmpty {
      failureMessage = Self.axSnapshotFailureMessage
    } else {
      failureMessage = "\(Self.axSnapshotFailureMessage) \(detail)"
    }
    return SnapshotCaptureFailure(
      code: Self.axSnapshotErrorCode,
      message: failureMessage,
      hint: Self.axSnapshotHint
    )
  }

  private static func isAxIllegalArgument(_ message: String) -> Bool {
    let normalized = message.lowercased()
    return normalized.contains("kaxerrorillegalargument")
      || (normalized.contains("illegal argument") && normalized.contains("snapshot"))
  }

  static func isAxSnapshotFailure(_ failure: SnapshotCaptureFailure) -> Bool {
    failure.code == Self.axSnapshotErrorCode || isAxIllegalArgument(failure.message)
  }

  func evaluateSnapshot(_ snapshot: XCUIElementSnapshot) -> SnapshotEvaluation {
    let label = aggregatedLabel(for: snapshot) ?? snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let identifier = snapshot.identifier.trimmingCharacters(in: .whitespacesAndNewlines)
    let valueText = Self.valueText(snapshot.value)
    return SnapshotEvaluation(
      label: label,
      identifier: identifier,
      valueText: valueText,
      placeholder: placeholderText(snapshot.placeholderValue),
      focused: snapshotHasFocus(snapshot),
      selected: snapshotIsSelected(snapshot)
    )
  }

  func makeSnapshotNode(
    snapshot: XCUIElementSnapshot,
    evaluation: SnapshotEvaluation,
    depth: Int,
    index: Int,
    parentIndex: Int?
  ) -> RawAXNode {


    return RawAXNode(
      index: index,
      type: elementTypeName(snapshot.elementType),
      label: evaluation.label.isEmpty ? nil : evaluation.label,
      identifier: evaluation.identifier.isEmpty ? nil : evaluation.identifier,
      value: evaluation.valueText,
      placeholder: evaluation.placeholder,
      rect: SnapshotRect(snapshot.frame),
      enabled: snapshot.isEnabled,
      focused: evaluation.focused ? true : nil,
      selected: evaluation.selected ? true : nil,
      hittable: false,
      depth: depth,
      parentIndex: parentIndex,
      hiddenContentAbove: nil,
      hiddenContentBelow: nil
    )
  }



  func capturedInterfaceOrientation(app: XCUIApplication) -> Int {
    safely("SNAPSHOT_INTERFACE_ORIENTATION", RunnerInterfaceOrientation.unknown) {
      Int(RunnerSynthesizedGesture.interfaceOrientation(forApplication: app))
    }
  }


  static func valueText(_ value: Any?) -> String? {
    guard let value else { return nil }
    let text = String(describing: value).trimmingCharacters(in: .whitespacesAndNewlines)
    return text.isEmpty ? nil : text
  }




  func placeholderText(_ placeholderValue: String?) -> String? {
    let text = placeholderValue?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
    return text.isEmpty ? nil : text
  }




  static let placeholderElementTypes: Set<XCUIElement.ElementType> = [
    .textField, .secureTextField, .searchField, .textView,
  ]

  func elementPlaceholderText(_ element: XCUIElement, type: XCUIElement.ElementType) -> String? {
    guard Self.placeholderElementTypes.contains(type) else { return nil }
    return placeholderText(element.placeholderValue)
  }

  private func snapshotAppFrame(app: XCUIApplication) throws -> CGRect {
#if os(iOS)
    return try onScreenWindowFrame(app: app)
#else
    return app.frame
#endif
  }

  private func aggregatedLabel(for snapshot: XCUIElementSnapshot, depth: Int = 0) -> String? {
    if depth > 4 { return nil }
    let text = snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    if !text.isEmpty { return text }
    if let valueText = Self.valueText(snapshot.value) { return valueText }
    for child in snapshot.children {
      if let childLabel = aggregatedLabel(for: child, depth: depth + 1) {
        return childLabel
      }
    }
    return nil
  }

  func appendCollapsedTabFallbackNodes(
    to nodes: inout [RawAXNode],
    containerSnapshot: XCUIElementSnapshot,
    resolveCandidates: () throws -> [CollapsedTabCandidate],
    depth: Int,
    parentIndex: Int
  ) throws {
    let fallbackNodes = try collapsedTabFallbackNodes(
      for: containerSnapshot,
      resolveCandidates: resolveCandidates,
      startingIndex: nodes.count,
      depth: depth,
      parentIndex: parentIndex
    )
    nodes.append(contentsOf: fallbackNodes)
  }


  static func snapshotDescendants(of root: XCUIElementSnapshot) -> [XCUIElementSnapshot] {
    var descendants: [XCUIElementSnapshot] = []
    var stack = Array(root.children.reversed())
    while let snapshot = stack.popLast() {
      descendants.append(snapshot)
      stack.append(contentsOf: snapshot.children.reversed())
    }
    return descendants
  }


  struct CollapsedTabCandidate {
    let type: XCUIElement.ElementType
    let frame: CGRect
    let label: String
    let identifier: String
    let valueText: String?
    let enabled: Bool
    let focused: Bool
    let selected: Bool
  }




  @MainActor
  func collapsedTabCandidates(
    context: SnapshotTraversalContext,
    processingDeadline: Date
  ) throws -> [CollapsedTabCandidate]? {
    let containerFrames = Self.snapshotDescendants(of: context.rootSnapshot)
      .filter(isCollapsedTabContainer)
      .map(\.frame)
    var candidates: [CollapsedTabCandidate] = []
    let predicate = Self.collapsedTabCandidatePredicate(containerFrames: containerFrames) { attributes in
      candidates.append(self.collapsedTabCandidate(attributes))
    }
    func canStartQuery() -> Bool {
      guard Self.xctestQueryCanStart(deadline: processingDeadline, now: Date(), expectedCost: context.rootReadDuration) else {
        NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_TAB_FALLBACK_QUERY_NOT_STARTED")
        return false
      }
      return true
    }
    guard canStartQuery() else { return nil }
    let queries = try elementQueries(
      root: context.queryRoot,
      matching: .any,
      litDisplayID: context.litPanelSurface?.displayID
    )
    var matches: [XCUIElement] = []
    for query in queries {
      guard canStartQuery() else { return nil }
      matches += snapshotElementsQuery {
        query.matching(predicate).allElementsBoundByIndex
      }.elements
    }
    return matches.isEmpty ? [] : candidates
  }

  private func collapsedTabCandidate(_ attributes: XCUIElementAttributes) -> CollapsedTabCandidate {
    CollapsedTabCandidate(
      type: attributes.elementType,
      frame: attributes.frame,
      label: attributes.label.trimmingCharacters(in: .whitespacesAndNewlines),
      identifier: attributes.identifier.trimmingCharacters(in: .whitespacesAndNewlines),
      valueText: Self.valueText(attributes.value),
      enabled: attributes.isEnabled,
      focused: focusBool(attributes as! NSObject),
      selected: attributes.isSelected
    )
  }





  static func collapsedTabCandidatePredicate(
    containerFrames: [CGRect],
    matched: @escaping (XCUIElementAttributes) -> Void
  ) -> NSPredicate {
    NSPredicate { object, _ in
      guard let attributes = object as? XCUIElementAttributes, hasCollapsedTabContent(attributes),
        containerFrames.contains(where: {
          isCollapsedTabCandidate(type: attributes.elementType, frame: attributes.frame, in: $0)
        })
      else {
        return false
      }
      matched(attributes)
      return true
    }
  }



  static func isCollapsedTabCandidate(
    type: XCUIElement.ElementType,
    frame: CGRect,
    in containerFrame: CGRect
  ) -> Bool {
    guard collapsedTabCandidateTypes.contains(type), !frame.isNull, !frame.isEmpty else {
      return false
    }
    let area = max(CGFloat(1), frame.width * frame.height)
    let containerArea = max(CGFloat(1), containerFrame.width * containerFrame.height)
    return area < containerArea * 0.9 && containerFrame.contains(CGPoint(x: frame.midX, y: frame.midY))
  }



  static func collapsedTabRowFits(midpoints: [Double], containerHeight: Double) -> Bool {
    let rowSpread = (midpoints.max() ?? 0) - (midpoints.min() ?? 0)
    return rowSpread <= max(24.0, containerHeight * 0.6)
  }



  static func hasCollapsedTabContent(_ attributes: XCUIElementAttributes) -> Bool {
    [attributes.label, attributes.identifier]
      .contains { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
      || valueText(attributes.value) != nil
  }

  private func collapsedTabFallbackNodes(
    for containerSnapshot: XCUIElementSnapshot,
    resolveCandidates: () throws -> [CollapsedTabCandidate],
    startingIndex: Int,
    depth: Int,
    parentIndex: Int
  ) throws -> [RawAXNode] {
    guard isCollapsedTabContainer(containerSnapshot) else { return [] }




    let containerFrame = containerSnapshot.frame
    let candidates = try resolveCandidates().compactMap { candidate in
      collapsedTabCandidateNode(
        candidate: candidate,
        containerSnapshot: containerSnapshot,
        containerFrame: containerFrame
      )
    }
    .sorted { left, right in
      if left.rect.x != right.rect.x {
        return left.rect.x < right.rect.x
      }
      return left.rect.y < right.rect.y
    }

    if candidates.count < 2 { return [] }
    let rowMidpoints = candidates.map { $0.rect.y + ($0.rect.height / 2) }
    if !Self.collapsedTabRowFits(midpoints: rowMidpoints, containerHeight: Double(containerFrame.height)) {
      return []
    }

    var seen = Set<String>()
    let uniqueCandidates = candidates.filter { node in
      let key = "\(node.type)-\(node.label ?? "")-\(node.identifier ?? "")-\(node.value ?? "")-\(node.rect.x)-\(node.rect.y)-\(node.rect.width)-\(node.rect.height)"
      if seen.contains(key) { return false }
      seen.insert(key)
      return true
    }
    if uniqueCandidates.count < 2 { return [] }

    return uniqueCandidates.enumerated().map { offset, node in
      node.reindexed(index: startingIndex + offset, depth: depth, parentIndex: parentIndex)
    }
  }

  private func collapsedTabCandidateNode(
    candidate: CollapsedTabCandidate,
    containerSnapshot: XCUIElementSnapshot,
    containerFrame: CGRect
  ) -> RawAXNode? {
    if !Self.isCollapsedTabCandidate(type: candidate.type, frame: candidate.frame, in: containerFrame) {
      return nil
    }
    if sameSemanticElement(
      containerSnapshot: containerSnapshot,
      elementType: candidate.type,
      label: candidate.label,
      identifier: candidate.identifier
    ) {
      return nil
    }



    return RawAXNode(
      index: 0,
      type: elementTypeName(candidate.type),
      label: candidate.label.isEmpty ? nil : candidate.label,
      identifier: candidate.identifier.isEmpty ? nil : candidate.identifier,
      value: candidate.valueText,
      placeholder: nil,
      rect: SnapshotRect(candidate.frame),
      enabled: candidate.enabled,
      focused: candidate.focused ? true : nil,
      selected: candidate.selected ? true : nil,
      hittable: false,
      depth: 0,
      parentIndex: nil,
      hiddenContentAbove: nil,
      hiddenContentBelow: nil
    )
  }

  func snapshotHasFocus(_ snapshot: XCUIElementSnapshot) -> Bool {
    return focusBool(snapshot as! NSObject)
  }


  func snapshotHasKeyboardFocus(_ snapshot: XCUIElementSnapshot) -> Bool {
    return kvcBool(snapshot as! NSObject, forKey: "hasKeyboardFocus")
  }







  func focusBool(_ object: NSObject) -> Bool {
    return kvcBool(object, forKey: "hasKeyboardFocus") || kvcBool(object, forKey: "hasFocus")
  }

  private func kvcBool(_ object: NSObject, forKey key: String) -> Bool {
    var result = false
    _ = RunnerObjCExceptionCatcher.catchException({
      if let value = object.value(forKey: key) as? Bool {
        result = value
      }
    })
    return result
  }

  private func snapshotIsSelected(_ snapshot: XCUIElementSnapshot) -> Bool {
    return snapshot.isSelected
  }


  func isCollapsedTabContainer(_ snapshot: XCUIElementSnapshot) -> Bool {
    if !snapshot.children.isEmpty { return false }
    let frame = snapshot.frame
    if frame.isNull || frame.isEmpty { return false }
    if frame.width < max(CGFloat(160), frame.height * 1.75) { return false }
    switch snapshot.elementType {
    case .tabBar, .segmentedControl:
      return true
    default:
      return false
    }
  }

  private func sameSemanticElement(
    containerSnapshot: XCUIElementSnapshot,
    elementType: XCUIElement.ElementType,
    label: String,
    identifier: String
  ) -> Bool {
    if containerSnapshot.elementType != elementType { return false }
    let containerLabel = containerSnapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let containerIdentifier = containerSnapshot.identifier
      .trimmingCharacters(in: .whitespacesAndNewlines)
    return containerLabel == label && containerIdentifier == identifier
  }

  @MainActor
  func flatInteractiveElements(
    app: XCUIApplication,
    deadline: Date
  ) -> (elements: [XCUIElement], outcome: SnapshotTierOutcome) {
    let queries: [XCUIElementQuery] = [
      app.buttons,
      app.links,
      app.textFields,
      app.secureTextFields,
      app.searchFields,
      app.textViews,
      app.switches,
      app.sliders,
      app.segmentedControls,
      app.cells,
      app.collectionViews,
      app.tables,
      app.scrollViews,
      app.pickers,
      app.steppers,
      app.tabBars,
      app.menuItems,
      app.staticTexts,
      app.images
    ]

    return Self.runFlatInteractiveQueries(queries, deadline: deadline) { query in
      self.snapshotElementsQuery {
        query.allElementsBoundByIndex
      }
    }
  }





  static func runFlatInteractiveQueries<Query, Element>(
    _ queries: [Query],
    deadline: Date,
    now: () -> Date = { Date() },
    run: (Query) -> (elements: [Element], axUnavailable: Bool)
  ) -> (elements: [Element], outcome: SnapshotTierOutcome) {
    var elements: [Element] = []
    for query in queries {
      if !xctestQueryCanStart(deadline: deadline, now: now()) {
        NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_FLAT_FALLBACK_DEADLINE")
        return (elements, .deadlineExhausted)
      }
      let result = run(query)
      elements.append(contentsOf: result.elements)
      if result.axUnavailable {
        break
      }
    }
    return (elements, .completed)
  }

  @MainActor
  func snapshotElementsQuery(
    _ fetch: () -> [XCUIElement]
  ) -> (elements: [XCUIElement], axUnavailable: Bool) {
    let (elements, exceptionMessage) = catchingObjCException(fallback: [], fetch)
    guard let exceptionMessage else {
      return (elements, false)
    }
    NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_QUERY_IGNORED_EXCEPTION=%@", exceptionMessage)
    if Self.isAxIllegalArgument(exceptionMessage) {
      invalidateCachedTarget(reason: "ax_snapshot_query_unavailable")
      return ([], true)
    }
    return ([], false)
  }

  func flatSnapshotNode(
    element: XCUIElement,
    index: Int,
    parentIndex: Int?
  ) -> RawAXNode? {
    var node: RawAXNode?
    let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
      if !element.exists { return }


      let frame = element.frame
      if frame.isNull || frame.isEmpty { return }
      let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
      let identifier = element.identifier.trimmingCharacters(in: .whitespacesAndNewlines)
      let valueText = Self.valueText(element.value)
      let elementType = element.elementType
      let enabled = element.isEnabled

      node = RawAXNode(
        index: index,
        type: elementTypeName(elementType),
        label: label.isEmpty ? nil : label,
        identifier: identifier.isEmpty ? nil : identifier,
        value: valueText,
        placeholder: elementPlaceholderText(element, type: elementType),
        rect: SnapshotRect(frame),
        enabled: enabled,
        focused: elementHasFocus(element) ? true : nil,
        selected: element.isSelected ? true : nil,
        hittable: false,
        depth: 1,
        parentIndex: parentIndex,
        hiddenContentAbove: nil,
        hiddenContentBelow: nil
      )
    })
    if let exceptionMessage {
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_FLAT_IGNORED_EXCEPTION=%@", exceptionMessage)
      return nil
    }
    return node
  }

}
