//! v3.17 c3 — dogfood usecase: setup → network select (mock SN onboarding).
//!
//! Port reference: `insight/tools/maestro/flows/setup/network-select.yaml`
//! & subflows (`launch-warm.yaml`, `ensure-login.yaml`, `go-to-add-device.yaml`,
//! `open-menu.yaml`). Drives the add-device → enter mock SN → submit →
//! arrive at network selection screen path:
//!
//! 1. launch-warm (terminate + deep-link openURL + wait landing/home)
//! 2. ensure_login (re-login if session expired)
//! 3. go_to_add_device (open drawer → tap "Add Device" → screen-add-device id)
//! 4. tap "Enter code" → tap id "input-sn" → fill "MOCK00010001" → tap "Add Device"
//! 5. extendedWaitUntil text-regex "Select Network|device not found" (30s)
//! 6. optional assertVisible "WiFi|Select Network" + "Continue"
//!
//! # Why this dogfood
//!
//! Setup/onboarding family first-証 — `Add Device` route is the gateway
//! to insight's device-provisioning flow. The yaml uses a **mock SN**
//! (`MOCK00010001`) to trigger insight's offline onboarding mock path,
//! so no real BLE/QR/server roundtrip happens. This gates two SDK
//! capabilities not yet dogfooded on a real-sim run:
//!
//! - `fill` against an id-selector input (`input-sn`)
//! - id-selector tap for the form submit button ("Add Device" text re-used
//!   on submit, distinct from drawer "Add Device")
//!
//! Also exercises the same drawer/menu pattern as sub-agent 1+2 examples,
//! re-証 the open-menu repeat-until-Dashboard loop is stable across
//! repeated dogfood example runs.
//!
//! # Reversibility
//!
//! Mock SN `MOCK00010001` is recognized by insight RN bundle as a sentinel
//! that triggers the **mock onboarding flow** (no server device created,
//! no BLE pairing attempt). Server state untouched. Flow ends on the
//! "Select Network" screen (or "device not found" branch); next dogfood
//! run starts with `launch_warm`'s `terminate` + deep-link which forces
//! cold-start of RN bundle, dropping any in-memory onboarding step state.
//!
//! # Capability gap surfaced
//!
//! None planned. If the iOS Camera permission system alert appears after
//! tapping drawer "Add Device" (same risk as sub-agent 1 menu_navigation
//! G9 cap-gap), the wait_for on id "screen-add-device" will time out
//! and the example fails fast — cap-gap is already filed (v4 swift cycle
//! `system_popup_dismiss` API). Do NOT graceful-skip here: the entire
//! flow's purpose IS to land on Add Device, so a blocking popup = full
//! flow unreachable, not a per-section skip.

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 network select (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_network_select_flow(&app).await {
        Ok(()) => {
            println!("\n✓ setup network select flow passed (1-round dogfood)");
            println!("\n🎉 v3.17 c3 dogfood — setup_network_select ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ setup network select flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood setup network select 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 drawer
/// "Add Device" → wait id "screen-add-device" (≤30s).
async fn go_to_add_device(app: &App) -> Result<(), ExpectationFailure> {
    open_menu(app).await?;
    app.tap(&text("Add Device")).await?;
    app.wait_for(&id("screen-add-device"), Duration::from_secs(30))
        .await?;
    Ok(())
}

// ---- setup-network-select flow (port of flows/setup/network-select.yaml) ----

async fn setup_network_select_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: drawer → Add Device → screen-add-device visible");
    go_to_add_device(app).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 2: tap 'Enter code' → SN entry form revealed");
    app.tap(&text("Enter code")).await?;
    // yaml: waitForAnimationToEnd — settle the reveal animation
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 3: tap id 'input-sn' to focus the SN text field");
    app.tap(&id("input-sn")).await?;
    tokio::time::sleep(Duration::from_millis(400)).await;

    println!("step 4: fill mock SN 'MOCK00010001' (triggers insight mock onboarding)");
    app.fill(&id("input-sn"), "MOCK00010001").await?;
    tokio::time::sleep(Duration::from_millis(400)).await;

    // G8 + DFS-first cap-gap: text("Add Device") has 3 candidates (title y=78 ×2 +
    // submit button y=796). DFS picks title not submit. Submit button is below
    // keyboard. Fix = hide_keyboard + tap_at_coord on submit centroid.
    println!(
        "step 5: tap submit 'Add Device' via hide_keyboard + tap_at_coord (G8 + DFS workaround)"
    );
    app.hide_keyboard().await?;
    tokio::time::sleep(Duration::from_millis(800)).await;
    app.tap_at_coord(0.5, 0.936).await?;

    println!("step 6: wait 'Select Network|device not found' (≤30s)");
    app.wait_for(
        &text_regex("Select Network|device not found"),
        Duration::from_secs(30),
    )
    .await?;

    println!("step 7: optional assertVisible 'WiFi|Select Network' (yaml optional: true)");
    // yaml `assertVisible: ... optional: true` semantics — failure is
    // tolerated. Map to `let _ = assert_visible(...)` so a missing branch
    // (e.g. device-not-found path) doesn't fail the example.
    let _ = app.assert_visible(&text_regex("WiFi|Select Network")).await;

    println!("step 8: optional assertVisible 'Continue' (yaml optional: true)");
    let _ = app.assert_visible(&text("Continue")).await;

    Ok(())
}
