import XCTest

final class RecordingWorkflowTests: XCTestCase {
    func testCalibrationRecordMarkersSaveExportCancelAndRelaunch() {
        let app = XCUIApplication()
        app.launchArguments = ["--uitest-motion"]
        app.launch()
        XCTAssertTrue(app.staticTexts["syntheticLabel"].waitForExistence(timeout: 5))
        calibrate(app)
        XCTAssertTrue(app.buttons["shareCalibrationLog"].exists)
        app.buttons["shareCalibrationLog"].tap()
        XCTAssertTrue(app.staticTexts["Save to Files"].waitForExistence(timeout: 10))
        app.otherElements["PopoverDismissRegion"].tap()
        app.buttons["startRecording"].doubleTap()
        XCTAssertTrue(app.staticTexts["recordingIndicator"].waitForExistence(timeout: 5))
        for label in ["LEFT", "CENTER", "RIGHT", "GOOD", "BAD"] { app.buttons["marker\(label)"].tap() }
        app.buttons["stopRecording"].doubleTap()
        XCTAssertTrue(app.staticTexts["savedSession"].waitForExistence(timeout: 10))
        XCTAssertTrue(app.staticTexts["savedEventCount"].label.contains("5 events"))
        app.buttons["exportSession"].tap()
        let close = app.buttons["Close"]
        XCTAssertTrue(close.waitForExistence(timeout: 10))
        close.tap()
        expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: close)
        waitForExpectations(timeout: 5)
        for _ in 0..<15 { if app.buttons["anotherRecording"].isHittable { break }; app.swipeUp() }
        expectation(for: NSPredicate(format: "hittable == true"), evaluatedWith: app.buttons["anotherRecording"])
        waitForExpectations(timeout: 5)
        app.buttons["anotherRecording"].tap()
        XCTAssertTrue(app.buttons["calibrate"].waitForExistence(timeout: 5))
        calibrate(app)
        app.buttons["startRecording"].tap()
        XCTAssertTrue(app.staticTexts["recordingIndicator"].waitForExistence(timeout: 5))
        XCUIDevice.shared.press(.home)
        app.activate()
        XCTAssertTrue(app.staticTexts["savedSession"].waitForExistence(timeout: 10))
        XCTAssertTrue(app.staticTexts["INTERRUPTED"].exists)
        app.terminate(); app.launch()
        app.buttons["sessions"].tap()
        let rows = app.descendants(matching: .any).matching(identifier: "sessionRow")
        XCTAssertGreaterThanOrEqual(rows.count, 2)
        rows.firstMatch.tap()
        XCTAssertTrue(app.staticTexts["savedSession"].waitForExistence(timeout: 10))
    }
    private func calibrate(_ app: XCUIApplication) {
        app.buttons["calibrate"].tap()
        XCTAssertFalse(app.buttons["continueCalibration"].exists)
        XCTAssertTrue(app.buttons["startRecording"].waitForExistence(timeout: 20))
    }
}
