import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  static let axSnapshotErrorCode = "IOS_AX_SNAPSHOT_FAILED"
  static let axSnapshotFailureMessage =
    "iOS XCTest snapshot failed while serializing the accessibility tree."
  static let axSnapshotUnavailableReason = "ax_snapshot_unavailable"
  static let axSnapshotHint =
    "Snapshot state is unavailable because XCTest could not serialize this iOS accessibility tree. This can be specific to the current screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth; navigate with coordinate commands if needed; then retry snapshot -i after reaching another screen. If you own the app and need full-tree inspection, simplify this screen's accessibility tree and expose stable ids on actionable controls."
  static let rawSnapshotTooLargeCode = "IOS_RAW_SNAPSHOT_TOO_LARGE"
  static let rawSnapshotMaxNodes = 5_000
  static let rawSnapshotTooLargeHint =
    "Raw iOS snapshot exceeded the runner payload guard. Use regular snapshot for visible UI, or scope/depth-limit raw snapshot when inspecting a large accessibility tree."


  private static let regularSnapshotMaxNodes = 50_000
  private static let regularSnapshotTooLargeCode = "IOS_SNAPSHOT_TOO_LARGE"
  private static let regularSnapshotTooLargeHint =
    "iOS snapshot walked an unexpectedly large accessibility tree. Scope the snapshot to a subtree or use screenshot."
  struct SnapshotTraversalContext {
    let queryRoot: XCUIElement
    let rootSnapshot: XCUIElementSnapshot

    let rootReadDuration: TimeInterval

    let viewport: SnapshotViewport





    let keyboardBand: RunnerKeyboardBandFact?

    var litPanelSurface: LitPanelSurface? = nil
  }

  struct SnapshotEvaluation {
    let label: String
    let identifier: String
    let valueText: String?
    let placeholder: String?
    let focused: Bool
    let selected: Bool
  }

  private struct SnapshotTraversalEntry {
    let snapshot: XCUIElementSnapshot
    let depth: Int
    let parentIndex: Int?
  }






  static func canDescendAtRawDepth(_ depth: Int, hint: CaptureHint) -> Bool {
    guard let rawLimit = hint.rawTraversalDepth else { return true }
    return depth < rawLimit
  }

  struct SnapshotCaptureFailure: Error {
    let code: String
    let message: String
    let hint: String
    let qualityReasonCode: String?

    init(code: String, message: String, hint: String, qualityReasonCode: String? = nil) {
      self.code = code
      self.message = message
      self.hint = hint
      self.qualityReasonCode = qualityReasonCode
    }
  }




  static let elementTypeNamesByRawValue = [
    XCUIElement.ElementType.application.rawValue: "Application",
    XCUIElement.ElementType.window.rawValue: "Window",
    XCUIElement.ElementType.button.rawValue: "Button",
    XCUIElement.ElementType.cell.rawValue: "Cell",
    XCUIElement.ElementType.staticText.rawValue: "StaticText",
    XCUIElement.ElementType.textField.rawValue: "TextField",
    XCUIElement.ElementType.textView.rawValue: "TextView",
    XCUIElement.ElementType.secureTextField.rawValue: "SecureTextField",
    XCUIElement.ElementType.switch.rawValue: "Switch",
    XCUIElement.ElementType.slider.rawValue: "Slider",
    XCUIElement.ElementType.link.rawValue: "Link",
    XCUIElement.ElementType.image.rawValue: "Image",
    XCUIElement.ElementType.navigationBar.rawValue: "NavigationBar",
    XCUIElement.ElementType.tabBar.rawValue: "TabBar",
    XCUIElement.ElementType.collectionView.rawValue: "CollectionView",
    XCUIElement.ElementType.table.rawValue: "Table",
    XCUIElement.ElementType.scrollView.rawValue: "ScrollView",
    XCUIElement.ElementType.toolbar.rawValue: "Toolbar",
    XCUIElement.ElementType.searchField.rawValue: "SearchField",
    XCUIElement.ElementType.segmentedControl.rawValue: "SegmentedControl",
    XCUIElement.ElementType.stepper.rawValue: "Stepper",
    XCUIElement.ElementType.picker.rawValue: "Picker",
    XCUIElement.ElementType.activityIndicator.rawValue: "ActivityIndicator",
    XCUIElement.ElementType.progressIndicator.rawValue: "ProgressIndicator",
    XCUIElement.ElementType.checkBox.rawValue: "CheckBox",
    XCUIElement.ElementType.radioButton.rawValue: "RadioButton",
    XCUIElement.ElementType.toggle.rawValue: "Toggle",
    XCUIElement.ElementType.menuItem.rawValue: "MenuItem",
    XCUIElement.ElementType.webView.rawValue: "WebView",
    XCUIElement.ElementType.other.rawValue: "Other",
    19: "Keyboard",
    20: "Key"
  ]

  func elementTypeName(_ type: XCUIElement.ElementType) -> String {
    Self.elementTypeNamesByRawValue[type.rawValue] ?? "Element(\(type.rawValue))"
  }

  static let structuralOnlyNodeTypes: Set<String> = [
    "Application",
    "Window",
    "Other",
    "ScrollView"
  ]

  static let collapsedTabCandidateTypes: Set<XCUIElement.ElementType> = [
    .button,
    .link,
    .menuItem,
    .other,
    .staticText
  ]

  static let scrollContainerTypes: Set<XCUIElement.ElementType> = [
    .collectionView,
    .scrollView,
    .table
  ]

  static let flatInteractiveFallbackBudget: TimeInterval = 1.0


  static let flatInteractiveQueryBudget: TimeInterval = 0.1



  static func querySweepSliceDeadline(startedAt: Date, planDeadline: Date) -> Date {
    min(startedAt.addingTimeInterval(flatInteractiveFallbackBudget), planDeadline)
  }




  static func xctestQueryCanStart(deadline: Date, now: Date, expectedCost: TimeInterval = 0) -> Bool {
    deadline.timeIntervalSince(now) >= max(flatInteractiveQueryBudget, expectedCost)
  }






  static let keyboardBandProbeBudget: TimeInterval = 0.3






  func snapshotFast(target: SnapshotCaptureTarget, options: PresentationOptions) throws -> DataPayload {
    try snapshotAfterSystemAlertTier(
      plan: Self.regularVisiblePlan,
      terminal: .sparseWithFatalOnAXFailure,
      target: target,
      options: options
    )
  }

  @MainActor
  func recursiveTreeSnapshotAcquisition(
    context: SnapshotTraversalContext,
    hint: CaptureHint,
    processingDeadline: Date
  ) throws -> (acquisition: SnapshotAcquisition, outcome: SnapshotTierOutcome) {
    var outcome = SnapshotTierOutcome.completed
    var cachedCollapsedTabCandidates: [CollapsedTabCandidate]?
    func collapsedTabCandidatesOnce() throws -> [CollapsedTabCandidate] {
      if let cachedCollapsedTabCandidates {
        return cachedCollapsedTabCandidates
      }
      let candidates = try collapsedTabCandidates(context: context, processingDeadline: processingDeadline)
      if candidates == nil { outcome = .deadlineExhausted }
      cachedCollapsedTabCandidates = candidates ?? []
      return candidates ?? []
    }




    var root = makeSnapshotNode(
      snapshot: context.rootSnapshot,
      evaluation: evaluateSnapshot(context.rootSnapshot),
      depth: 0,
      index: 0,
      parentIndex: nil
    )
    Self.publishLitPanelRoot(&root, surface: context.litPanelSurface)
    let rootChildren = try Self.litPanelRootChildren(context.rootSnapshot, surface: context.litPanelSurface)
    var nodes: [RawAXNode] = [root]
    if Self.canDescendAtRawDepth(0, hint: hint) {
      try appendCollapsedTabFallbackNodes(
        to: &nodes,
        containerSnapshot: context.rootSnapshot,
        resolveCandidates: collapsedTabCandidatesOnce,
        depth: 1,
        parentIndex: 0
      )
    }

    var regularTree = RegularSnapshotTree(policy: .platformDefault)
    var stack: [SnapshotTraversalEntry] = []
    if Self.canDescendAtRawDepth(0, hint: hint) {
      stack = rootChildren.map {
        SnapshotTraversalEntry(snapshot: $0, depth: 1, parentIndex: 0)
      }
    }

    while let entry = stack.popLast() {
      let snapshot = entry.snapshot
      let depth = entry.depth
      if let limit = hint.rawTraversalDepth, depth > limit { continue }

      let evaluation = evaluateSnapshot(snapshot)
      let node = makeSnapshotNode(
        snapshot: snapshot,
        evaluation: evaluation,
        depth: depth,
        index: nodes.count,
        parentIndex: entry.parentIndex
      )
      let included = regularTree.append(node, elementType: String(describing: snapshot.elementType), to: &nodes)
      let currentIndex = included ? node.index : entry.parentIndex
      for child in snapshot.children.reversed() {
        stack.append(
          SnapshotTraversalEntry(snapshot: child, depth: depth + 1, parentIndex: currentIndex)
        )
      }

      if !included { continue }
      if nodes.count > Self.regularSnapshotMaxNodes {
        throw regularSnapshotTooLargeFailure(nodeCount: nodes.count)
      }
      if Self.canDescendAtRawDepth(depth, hint: hint) {
        try appendCollapsedTabFallbackNodes(
          to: &nodes,
          containerSnapshot: snapshot,
          resolveCandidates: collapsedTabCandidatesOnce,
          depth: depth + 1,
          parentIndex: node.index
        )
      }
    }

    return (
      SnapshotAcquisition(
        hint: hint,
        nodes: nodes,
        truncated: outcome == .deadlineExhausted,
        effectiveDepth: nil,
        viewport: context.viewport
      ),
      outcome
    )
  }


  static func publishLitPanelRoot(_ root: inout RawAXNode, surface: LitPanelSurface?) {
    if let surface {
      root.rect = SnapshotRect(surface.geometry.windowOnScreen.rect)
    }
  }


  static func litPanelRootChildren(
    _ root: XCUIElementSnapshot,
    surface: LitPanelSurface?
  ) throws -> [XCUIElementSnapshot] {
    guard let surface else { return root.children }
    let lit = windowsOnLitDisplay(root.children, litDisplayID: surface.displayID) { snapshotDisplayID($0) }
    if lit.isEmpty {
      throw RunnerAppScreenCaptureFailure.unresolvedScreen
    }
    return lit
  }


  static func windowsOnLitDisplay<Window>(
    _ windows: [Window],
    litDisplayID: UInt,
    displayID: (Window) -> UInt?
  ) -> [Window] {
    windows.filter { displayID($0) == litDisplayID }
  }


  static func snapshotDisplayID(_ snapshot: XCUIElementSnapshot) -> UInt? {
    var displayID: UInt?
    _ = RunnerObjCExceptionCatcher.catchException({
      displayID = ((snapshot as AnyObject).value(forKey: "displayID") as? NSNumber)?.uintValue
    })
    return displayID.flatMap { $0 == 0 ? nil : $0 }
  }


  func snapshotRaw(target: SnapshotCaptureTarget, options: PresentationOptions) throws -> DataPayload {
    try snapshotAfterSystemAlertTier(
      plan: Self.rawDiagnosticPlan,
      terminal: .throwOnAXFailure,
      target: target,
      options: options
    )
  }

  private func snapshotAfterSystemAlertTier(
    plan: [SnapshotBackendKind],
    terminal: SnapshotCaptureTerminalPolicy,
    target: SnapshotCaptureTarget,
    options: PresentationOptions
  ) throws -> DataPayload {
    let deadline = Date().addingTimeInterval(Self.snapshotPlanBudget)
    if let blocking = boundedBlockingSystemAlertSnapshot(
      deadline: deadline,
      penaltyTarget: .prepared(bundleId: target.bundleId),
      options: options
    ) {
      if target.refusesSystemAlertSubstitution {
        throw SystemAlertSubstitutionRefused()
      }
      return blocking
    }
    return try runSnapshotCapturePlan(
      plan,
      target: target,
      options: options,
      terminal: terminal,
      deadline: deadline
    )
  }




  func boundedBlockingSystemAlertSnapshot(
    deadline: Date,
    penaltyTarget: SnapshotProbePenaltyTarget,
    options: PresentationOptions
  ) -> DataPayload? {
    boundedBlockingSystemAlertSnapshotBody(
      deadline: deadline,
      penaltyTarget: penaltyTarget
    ) { probeDeadline in





      return try self.blockingSystemAlertSnapshot(options: options, deadline: probeDeadline)
    }
  }






  private func boundedBlockingSystemAlertSnapshotBody(
    deadline: Date,
    penaltyTarget: SnapshotProbePenaltyTarget,
    probe: @escaping @MainActor (Date) throws -> DataPayload?
  ) -> DataPayload? {
    #if os(macOS)
      return nil
    #else
    let slice = Self.systemModalProbeSlice(
      budget: systemModalProbeBudget,
      deadlineRemaining: deadline.timeIntervalSinceNow
    )
    guard slice > 0 else {
      NSLog("AGENT_DEVICE_RUNNER_SYSTEM_MODAL_PROBE_SKIPPED reason=budget_exhausted")
      return nil
    }
    let probeDeadline = Date().addingTimeInterval(slice)
    let startedAt = Date()
    let penaltyIdentity = SnapshotProbePenaltyIdentity(penaltyTarget)
    do {
      return try runMainThreadWork(
        "system_modal_probe",
        timeout: slice,
        timeoutError: {
          SnapshotCaptureFailure(
            code: Self.xCTestSnapshotTimeoutCode,
            message: "the system-modal probe exceeded its \(slice)s time slice",
            hint: "The capture plan recovers through non-XCTest snapshot tiers while the modal probe drains."
          )
        },
        onAbandoned: {
          self.penalizeSnapshotXCTestChannel(
            bundleId: penaltyIdentity.penalizedBundleId,
            reason: "system_modal_probe_timeout"
          )
        }
      ) {
        penaltyIdentity.captureFromMain(bundleId: self.mainOwned.bundleId)
        return try probe(probeDeadline)
      }
    } catch {
      NSLog(
        "AGENT_DEVICE_RUNNER_SYSTEM_MODAL_PROBE_ABORTED elapsedMs=%d error=%@",
        Int(Date().timeIntervalSince(startedAt) * 1000),
        String(describing: error)
      )
      return nil
    }
    #endif
  }



  static func systemModalProbeSlice(
    budget: TimeInterval,
    deadlineRemaining: TimeInterval
  ) -> TimeInterval {
    guard deadlineRemaining > 0 else { return 0 }
    return min(budget, deadlineRemaining)
  }

  func rawTreeSnapshotAcquisition(
    context: SnapshotTraversalContext,
    hint: CaptureHint
  ) throws -> SnapshotAcquisition {
    var nodes: [RawAXNode] = []

    func walk(
      _ snapshot: XCUIElementSnapshot,
      depth: Int,
      parentIndex: Int?,
      children: [XCUIElementSnapshot]? = nil
    ) throws {
      if let limit = hint.rawTraversalDepth, depth > limit { return }

      let evaluation = evaluateSnapshot(snapshot)
      if nodes.count >= Self.rawSnapshotMaxNodes {
        throw rawSnapshotTooLargeFailure(nodeCount: nodes.count + 1)
      }
      let currentIndex = nodes.count
      nodes.append(
        makeSnapshotNode(
          snapshot: snapshot,
          evaluation: evaluation,
          depth: depth,
          index: currentIndex,
          parentIndex: parentIndex
        )
      )

      for child in children ?? snapshot.children {
        try walk(
          child,
          depth: depth + 1,
          parentIndex: currentIndex
        )
      }
    }

    try walk(
      context.rootSnapshot,
      depth: 0,
      parentIndex: nil,
      children: try Self.litPanelRootChildren(context.rootSnapshot, surface: context.litPanelSurface)
    )
    if !nodes.isEmpty {
      Self.publishLitPanelRoot(&nodes[0], surface: context.litPanelSurface)
    }
    return SnapshotAcquisition(
      hint: hint,
      nodes: nodes,
      truncated: false,
      effectiveDepth: nil,
      viewport: context.viewport
    )
  }

  @MainActor
  func querySweepSnapshotAcquisition(
    app: XCUIApplication,
    hint: CaptureHint,
    sliceDeadline deadline: Date
  ) throws -> (acquisition: SnapshotAcquisition, outcome: SnapshotTierOutcome) {
    var nodes: [RawAXNode] = [
      interactiveRootNode(rect: .zero)
    ]
    if hint.rawTraversalDepth == 0 || hint.regularPresentedDepth == 0 {
      return (
        SnapshotAcquisition(
          hint: hint,
          nodes: nodes,
          truncated: false,
          effectiveDepth: nil,
          viewport: .missing(reason: .notProvided)
        ),
        .completed
      )
    }

    let viewport = try safeSnapshotViewport(app: app, readingOrientation: false)
    var seen = Set<String>()
    var candidates: [RawAXNode] = []
    let flatElements = flatInteractiveElements(app: app, deadline: deadline)
    var outcome = flatElements.outcome
    for element in flatElements.elements {
      if !Self.xctestQueryCanStart(deadline: deadline, now: Date()) {
        NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_FLAT_FALLBACK_DEADLINE")
        outcome = .deadlineExhausted
        break
      }
      guard let node = flatSnapshotNode(element: element, index: 0, parentIndex: 0) else {
        continue
      }
      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) { continue }
      seen.insert(key)
      candidates.append(node)
    }
    candidates.sort { left, right in
      if left.rect.y != right.rect.y {
        return left.rect.y < right.rect.y
      }
      if left.rect.x != right.rect.x {
        return left.rect.x < right.rect.x
      }
      return left.type < right.type
    }




    let rootRect = viewport.rect ?? interactiveRootFrame(for: candidates)
    nodes[0] = interactiveRootNode(rect: rootRect)
    for candidate in candidates {
      nodes.append(
        candidate.reindexed(index: nodes.count, depth: 1, parentIndex: 0)
      )
    }
    return (
      SnapshotAcquisition(
        hint: hint,
        nodes: nodes,
        truncated: outcome == .deadlineExhausted,
        effectiveDepth: nil,
        viewport: viewport
      ),
      outcome
    )
  }

  func snapshotAccessibilityUnavailable(failure: SnapshotCaptureFailure) -> DataPayload {
    NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_AX_UNAVAILABLE=%@", failure.message)
    applyMainOwnedSnapshotState("ax_unavailable_invalidation") {
      self.mainOwned.accessibilityHealth = .unavailable
      self.invalidateCachedTarget(reason: Self.axSnapshotUnavailableReason)
    }


    return sparseTruncatedSnapshotPayload(
      message: recoveredSnapshotMessage(failure),
      snapshotQuality: SnapshotQuality(
        state: .sparse,
        backend: SnapshotBackendKind.recursiveTree.rawValue,
        reason: failure.message,
        reasonCode: "ax-rejected",
        effectiveDepth: nil,
        collapsedLeafIndexes: nil,
        customActions: nil
      ),
      runnerFatal: true,
      runnerFatalReason: Self.axSnapshotUnavailableReason
    )
  }

  func recoveredSnapshotMessage(_ failure: SnapshotCaptureFailure) -> String {
    return "\(failure.message) Hint: \(failure.hint)"
  }

  func rawSnapshotTooLargeFailure(nodeCount: Int) -> SnapshotCaptureFailure {
    SnapshotCaptureFailure(
      code: Self.rawSnapshotTooLargeCode,
      message: "iOS raw snapshot exceeded \(Self.rawSnapshotMaxNodes) nodes while walking node \(nodeCount).",
      hint: Self.rawSnapshotTooLargeHint
    )
  }

  private func regularSnapshotTooLargeFailure(nodeCount: Int) -> SnapshotCaptureFailure {
    SnapshotCaptureFailure(
      code: Self.regularSnapshotTooLargeCode,
      message: "iOS snapshot exceeded \(Self.regularSnapshotMaxNodes) nodes while walking node \(nodeCount).",
      hint: Self.regularSnapshotTooLargeHint
    )
  }

  func sparseTruncatedSnapshotPayload(
    message: String? = nil,
    snapshotQuality: SnapshotQuality? = nil,
    runnerFatal: Bool? = nil,
    runnerFatalReason: String? = nil
  ) -> DataPayload {
    return DataPayload(
      message: message,
      nodes: [SnapshotPresentation.singleElementRead(interactiveRootNode(rect: .zero))],
      truncated: true,
      snapshotQuality: snapshotQuality,
      runnerFatal: runnerFatal,
      runnerFatalReason: runnerFatalReason
    )
  }
}
