import XCTest

@MainActor
final class SessionSwitcherUITests: XCTestCase {

    override func setUpWithError() throws {
        continueAfterFailure = false
    }

    func testSessionSwitcherFlow() throws {
        let app = XCUIApplication()
        app.launchPaired()

        // 1. Open Switcher
        let switcherButton = app.buttons["Switcher"]
        XCTAssertTrue(switcherButton.waitForExistence(timeout: 10))
        switcherButton.tap()

        // 2. Assert Navigation Title
        let navTitle = app.staticTexts["Sessions"]
        XCTAssertTrue(navTitle.waitForExistence(timeout: 5), "Session switcher sheet should have title 'Sessions'")

        // 3. Assert existing sessions
        let mainSession = app.staticTexts["main"]
        let workSession = app.staticTexts["work"]
        let logsSession = app.staticTexts["logs"]

        XCTAssertTrue(mainSession.exists, "Session 'main' should be present")
        XCTAssertTrue(workSession.exists, "Session 'work' should be present")
        XCTAssertTrue(logsSession.exists, "Session 'logs' should be present")

        // 4. Select 'main' and verify dismissal
        mainSession.tap()
        XCTAssertFalse(navTitle.waitForExistence(timeout: 5), "Sheet should dismiss after selecting a session")

        // 5. Create new session
        switcherButton.tap()
        let addButton = app.buttons["New Session"]
        XCTAssertTrue(addButton.waitForExistence(timeout: 5))
        addButton.tap()

        let nameField = app.textFields["Session name"]
        XCTAssertTrue(nameField.waitForExistence(timeout: 5))
        nameField.tap()
        let uniqueName = "uitest-\(Int(Date().timeIntervalSince1970))"
        nameField.typeText(uniqueName)

        let createButton = app.buttons["Create"]
        XCTAssertTrue(createButton.exists)
        createButton.tap()

        // 6. Verify new session appears (refresh runs async after spawn;
        // allow extra time for the sidecar round-trip + list rerender).
        let newSession = app.staticTexts[uniqueName]
        if !newSession.waitForExistence(timeout: 15) {
            // Capture diagnostic info to file before failing
            let screenshot = XCUIScreen.main.screenshot()
            let att = XCTAttachment(screenshot: screenshot)
            att.lifetime = .keepAlways
            att.name = "session-switcher-failure"
            add(att)
            let hierarchy = XCTAttachment(string: app.debugDescription)
            hierarchy.lifetime = .keepAlways
            hierarchy.name = "hierarchy"
            add(hierarchy)
            XCTFail("New session '\(uniqueName)' should appear in the list")
        }

        // Cleanup: delete via sidecar API
        TestSidecar.deleteSession(uniqueName)
    }
}
