//! v3.17 c3 — dogfood usecase: setup add device entry (nav + mode toggle).
//!
//! Port reference: `insight/tools/maestro/flows/setup/add-device-entry.yaml`
//! & subflows `launch-warm.yaml`, `ensure-login.yaml`, `open-menu.yaml`.
//! Drives:
//!
//! 1. launch-warm (terminate + openurl deep link + wait landing/home)
//! 2. ensure-login (double-check pattern, dev-bubble → Login if visible)
//! 3. open-menu (drawer open, repeat-until-Dashboard bounded 5×)
//! 4. tap "Add Device" → wait `screen-add-device` (≤30s)
//! 5. assert "Add Device" title visible
//! 6. tap "Enter code" → wait 800ms (mode switch animation)
//! 7. tap "Scan code" → wait 800ms (mode switch animation)
//!
//! # Why this dogfood
//!
//! Setup-side write-path entry first-証. yaml 本身只 nav + 模式切换，**不**
//! 实际提交 device add（无 code 输入 / 无 submit / 无 server mutation），
//! 所以归属 read-ish probe，跨次 run 无累积 state。Animated.Text 子组件
//! ("Enter code" / "Scan code") yaml 标注 "taps work even though invisible
//! to assertions" — smix SDK `app.tap(&text(...))` 经 a11y label 命中
//! Animated.Text underlying static text，与 maestro 同源行为，此 example
//! 也是该 invisible-but-tappable 模式的首个 SDK 表面確認。
//!
//! # Reversibility
//!
//! Pure nav + mode toggle — Add Device screen 仅 form 显示，无 commit。
//! "Enter code" / "Scan code" 模式切换是本地 view state，不写后端。
//! 结尾停留在 Add Device "Scan code" 模式，下次 run 由 launch-warm 重新
//! 起 app（terminate + deep link 重启），无 cross-test 残留。
//!
//! # Capability gap surfaced
//!
//! None planned。Animated.Text invisible-to-assert 但 tappable 是 RN
//! 渲染层的真实行为，maestro 同源处理，smix 通过 a11y label-based tap
//! 直接覆盖，不需额外 selector 表面。若实跑发现 tap 不命中 Animated.Text
//! （a11y label 未冒泡），则属 G-cap-gap，需 smix core 补 RN-aware
//! selector fallback（留至发现时再立案）。

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 add device entry (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_add_device_entry_flow(&app).await {
        Ok(()) => {
            println!("\n✓ setup add device entry flow passed (1-round dogfood)");
            println!("\n🎉 v3.17 c3 dogfood — setup_add_device_entry ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ setup add device entry flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood setup add device entry 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(())
}

// ---- setup-add-device-entry flow (port of flows/setup/add-device-entry.yaml) ----

async fn setup_add_device_entry_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: open drawer (open-menu subflow)");
    open_menu(app).await?;

    println!("step 2: tap 'Add Device' → wait screen-add-device id (≤30s)");
    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?;

    println!("step 3: assert 'Add Device' title visible (regular Text)");
    app.assert_visible(&text("Add Device")).await?;

    println!("step 4: tap 'Enter code' (Animated.Text — tappable, invisible to asserts)");
    app.tap(&text("Enter code")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 5: tap 'Scan code' (Animated.Text — switch back)");
    app.tap(&text("Scan code")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    Ok(())
}
