import XCTest

final class WatchWorkflowTests: XCTestCase {
    func testRuntimeProbeStartsRecordingWithoutTouch() {
        let app = XCUIApplication()
        app.launchArguments = ["--uitest-motion", "--runtime-probe"]
        app.launch()
        let stop = app.buttons["watchStop"]
        XCTAssertTrue(stop.waitForExistence(timeout: 10), "The diagnostic launch flag must actually start capture")
        stop.tap()
        XCTAssertTrue(app.buttons["Send to iPhone"].waitForExistence(timeout: 10))
        app.terminate()
    }
    func testCalibrateRecordSaveAndReview() {
        let app = XCUIApplication()
        app.launchArguments = ["--uitest-motion"]
        app.launch()
        let calibrate = app.buttons["watchCalibrate"]
        XCTAssertTrue(calibrate.waitForExistence(timeout: 5))
        XCTAssertTrue(calibrate.isHittable, "Calibration should be visible without scrolling")
        let audio = app.buttons["watchTestAudio"]
        XCTAssertTrue(audio.isHittable, "Audio check should be visible before mounting")
        let home = XCTAttachment(screenshot: app.screenshot())
        home.name = "watch-calibration-home"; home.lifetime = .keepAlways; add(home)
        audio.tap()
        // Watch XCTest tap scrolls the element into view; pre-scroll hit testing
        // can report false for a valid button outside the small viewport.
        calibrate.tap()
        let record = app.buttons["watchRecord"]
        XCTAssertTrue(record.waitForExistence(timeout: 20))
        record.tap()
        let stop = app.buttons["watchStop"]
        XCTAssertTrue(stop.waitForExistence(timeout: 5))
        stop.tap()
        XCTAssertTrue(app.buttons["Send to iPhone"].waitForExistence(timeout: 10))
        let summary = app.staticTexts["watchSavedSummary"]
        let receipt = NSPredicate(format: "label CONTAINS 'completed' AND label CONTAINS 'samples'")
        expectation(for: receipt, evaluatedWith: summary)
        waitForExpectations(timeout: 5)
        let screenshot = XCTAttachment(screenshot: app.screenshot())
        screenshot.name = "watch-saved-session"; screenshot.lifetime = .keepAlways; add(screenshot)
        app.terminate(); app.launch()
        let saved = app.buttons["Saved sessions"]
        saved.tap()
        XCTAssertGreaterThan(app.cells.count, 0)
    }
}
