//! v3.17 c3 — dogfood usecase: setup enter-SN form.
//!
//! Port reference: `insight/tools/maestro/flows/setup/enter-sn.yaml`. Drives
//! the Add Device → Enter code form flow:
//!
//! 1. launch-warm → ensure-login → go-to-add-device (drawer → "Add Device")
//! 2. tap "Enter code" sub-tab → wait animation
//! 3. assertVisible "Serial Number" + "XXXX-XXXX-XXXX" (form scaffolding)
//! 4. tap `input-sn` → fill "ABCD" (partial — button stays disabled)
//! 5. clear → fill "ABCD1234EFGH" (full 12-char SN)
//! 6. assertVisible "Add Device" (submit button label)
//!
//! # Why this dogfood
//!
//! Exercises the **text-input** capability surface — tap-to-focus,
//! incremental `inputText`, and `eraseText` clear-and-retype. The yaml's
//! `eraseText: 10` (delete 10 characters via backspace) maps to smix
//! `App::clear()` which empties the whole field — equivalent end state
//! since "ABCD" length is 4 ≤ 10, plus the subsequent `fill("ABCD1234EFGH")`
//! produces identical visible text. Also covers id-selector text input
//! (`id: "input-sn"`) which is the canonical RN `testID` → a11y id route.
//!
//! # Reversibility
//!
//! **Pure read** for the device-side: yaml only fills the SN form, does
//! **not** tap the "Add Device" submit button (final step is just
//! `assertVisible: "Add Device"`, no `tapOn`). No device gets paired to
//! the test account, no server mutation. Form state is local component
//! state and is discarded on next `reset_to_home`/`launch-warm`.
//!
//! # Capability gap surfaced
//!
//! - Inherits the v3.17 c1 G9 cap-gap: drawer → "Add Device" can trigger
//!   the iOS Camera permission alert (SpringBoard system popup). smix
//!   core lacks `system_popup_dismiss` (v3.x swift-frozen). Same
//!   detect-and-graceful-skip pattern applied in `go_to_add_device`
//!   helper below.
//! - `eraseText: N` (delete-N-chars granular) has no exact smix
//!   counterpart — `clear()` is whole-field. End state is equivalent
//!   here because the subsequent `fill` overwrites entirely. If a
//!   future flow needs partial backspace (e.g. correct only last char
//!   while preserving prefix), v4 SDK should add `App::backspace(n)`.

use smix_sdk::{App, ExpectationFailure, id, text, text_regex};
use std::time::Duration;

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let port: u16 = std::env::var("SMIX_RUNNER_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(22087);
    let udid = std::env::var("SMIX_UDID").ok();

    println!("smix dogfood — insight setup enter-sn (v3.17 c3)");
    println!("==================================================");
    println!("runner port: {port}");
    println!("udid:        {:?}", udid);
    println!();

    let mut app = App::connect_to_runner(port).await?;
    if let Some(u) = udid {
        app = app.with_udid(u);
    }

    let bundle_id =
        std::env::var("INSIGHT_BUNDLE_ID").unwrap_or_else(|_| "com.focusai.app.mobile".to_string());
    println!("launch-warm: terminate + openurl deep link");
    let _ = app.terminate(&bundle_id).await;
    tokio::time::sleep(Duration::from_millis(800)).await;
    app.open_url("exp+focus-ai-app://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8081")
        .await?;
    app.wait_for(
        &text_regex("Log in to Insight|Device|Open menu"),
        Duration::from_secs(45),
    )
    .await?;

    println!("ensure_login: starting");
    ensure_login(&app).await?;
    println!("ensure_login: done\n");

    println!("reset_to_home");
    reset_to_home(&app).await?;
    println!("reset_to_home: done\n");

    println!("close_dev_menu_if_open");
    close_dev_menu_if_open(&app).await?;
    println!("close_dev_menu_if_open: done\n");

    match setup_enter_sn_flow(&app).await {
        Ok(()) => {
            println!("\n✓ setup enter-sn flow passed (1-round dogfood)");
            println!("\n🎉 v3.17 c3 dogfood — setup_enter_sn ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ setup enter-sn flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood setup enter-sn FAIL".into())
        }
    }
}

// ---- inline helpers (each example self-contained) -----------------------

async fn ensure_login(app: &App) -> Result<(), ExpectationFailure> {
    // v3.14 c2 robust pattern: double-check login_text + dev_bubble both
    // visible. `find` (Apple element query) can flash login text for a
    // single tick during RN home-screen mount even when session cached.
    // Insist on dev-bubble; if gone, already authenticated.
    let login_text_visible = app.find(&text("Log in to Insight")).await?;
    let dev_bubble_visible = app.find(&id("dev-bubble")).await?;
    if !(login_text_visible && dev_bubble_visible) {
        println!("  already logged in (login screen not stable)");
        return Ok(());
    }
    println!("  tapping dev-bubble");
    app.tap(&id("dev-bubble")).await?;
    tokio::time::sleep(Duration::from_millis(1500)).await;
    println!("  tapping 'Login'");
    app.tap(&text("Login")).await?;
    println!("  waiting for home tab");
    app.wait_for(
        &text_regex("Open menu|Device|Search|Merlin|Alerts|Tracking"),
        Duration::from_secs(30),
    )
    .await?;
    Ok(())
}

async fn reset_to_home(app: &App) -> Result<(), ExpectationFailure> {
    for _ in 0..3 {
        let drawer_open = app
            .wait_for(&text("Dashboard"), Duration::from_millis(200))
            .await
            .is_ok();
        if !drawer_open {
            break;
        }
        let _ = app.go_back().await;
        tokio::time::sleep(Duration::from_millis(400)).await;
    }
    if app.find(&text("Device")).await? {
        let _ = app.tap(&text("Device")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    // v3.14 c2 robust fallback: any bottom-tab label (insight RN bundle
    // dropped `Open menu` label on some screens; Merlin tab header lacks it).
    app.wait_for(
        &text_regex("Open menu|Device|Search|Merlin|Alerts|Tracking"),
        Duration::from_secs(5),
    )
    .await?;
    Ok(())
}

async fn close_dev_menu_if_open(app: &App) -> Result<(), ExpectationFailure> {
    let open = app
        .wait_for(&text("Reboot"), Duration::from_millis(300))
        .await
        .is_ok();
    if open {
        println!("  dev menu visible, tapping dev-bubble");
        app.tap(&id("dev-bubble")).await?;
        tokio::time::sleep(Duration::from_millis(800)).await;
    } else {
        println!("  dev menu already dismissed");
    }
    Ok(())
}

/// Mirror of `subflows/open-menu.yaml`: wait for `btn-open-menu`, then
/// repeat-until-Dashboard-visible pattern bounded to 5 iterations.
async fn open_menu(app: &App) -> Result<(), ExpectationFailure> {
    tokio::time::sleep(Duration::from_millis(800)).await;
    app.wait_for(&id("btn-open-menu"), Duration::from_secs(30))
        .await?;
    for _ in 0..5 {
        if app
            .wait_for(&text("Dashboard"), Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Open menu")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    app.wait_for(&text("Dashboard"), Duration::from_secs(5))
        .await?;
    Ok(())
}

/// Mirror of `subflows/go-to-add-device.yaml`: open-menu → tap "Add Device"
/// → wait `screen-add-device` id (30s timeout, matching maestro
/// `extendedWaitUntil`). Inherits the v3.17 c1 G9 cap-gap workaround:
/// iOS Camera permission alert may appear; if it does, the post-tap
/// wait_for will fail and the caller treats this as a known cap-gap
/// (v4 swift cycle adds system_popup_dismiss).
async fn go_to_add_device(app: &App) -> Result<(), ExpectationFailure> {
    open_menu(app).await?;
    app.tap(&text("Add Device")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;
    app.wait_for(&id("screen-add-device"), Duration::from_secs(30))
        .await?;
    Ok(())
}

// ---- setup enter-sn flow (port of flows/setup/enter-sn.yaml) ------------

async fn setup_enter_sn_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: nav to Add Device (launch-warm + ensure-login + go-to-add-device)");
    go_to_add_device(app).await?;

    println!("step 2: switch to 'Enter code' sub-tab");
    app.tap(&text("Enter code")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 3: assertVisible form scaffolding ('Serial Number' + 'XXXX-XXXX-XXXX')");
    app.assert_visible(&text("Serial Number")).await?;
    app.assert_visible(&text("XXXX-XXXX-XXXX")).await?;

    println!("step 4: tap input-sn → fill partial 'ABCD' (button should stay disabled)");
    app.tap(&id("input-sn")).await?;
    app.fill(&id("input-sn"), "ABCD").await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 5: clear → fill full 'ABCD1234EFGH' (12-char SN)");
    // yaml uses `eraseText: 10` (backspace 10 times) — smix clear() empties
    // the whole field; end state equivalent since "ABCD" is 4 chars ≤ 10
    // and the subsequent fill overwrites entirely.
    app.clear(&id("input-sn")).await?;
    app.fill(&id("input-sn"), "ABCD1234EFGH").await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 6: assertVisible 'Add Device' (submit button label, NOT tapped)");
    app.assert_visible(&text("Add Device")).await?;

    Ok(())
}
