//! v3.17 c1 — dogfood usecase: tabs navigation (bottom-tab traversal).
//!
//! Port reference: `insight/tools/maestro/flows/main/tabs-navigation.yaml`
//! & subflows `launch-warm.yaml`, `ensure-login.yaml`, `go-to-search.yaml`,
//! `go-to-merlin.yaml`, `go-to-alerts.yaml`, `go-to-tracking.yaml`. Drives
//! the four non-default bottom tabs in sequence — Search → Merlin →
//! Alerts → Tracking — each via repeat-tap-until-landmark-visible.
//!
//! # Why this dogfood
//!
//! Bottom-tab traversal is the most basic navigation contract every
//! insight user encounters within seconds of launch. Maestro covers it
//! with one tiny yaml composing four subflows; smix must port the same
//! contract end-to-end through SDK → SimctlDriver → runner without
//! a single coord tap and without per-tab special-casing — proving that
//! repeat-while-notVisible is expressible as plain `wait_for` polling
//! over a per-tab landmark selector.
//!
//! Each subflow's landmark is a stable post-mount artifact:
//! - Search → text regex "People|Vehicle" (filter chips)
//! - Merlin → text "AI Assistant" (chat header)
//! - Alerts → id "screen-alerts" (root container)
//! - Tracking → id "btn-floor-plan-selector" (map control)
//!
//! Five-round cap mirrors empirical maestro retry budget — a single
//! missed tap (e.g. RN tab-bar mid-mount) usually settles within 1-2
//! rounds, 5 leaves slack for cold-startup jank.
//!
//! # Reversibility
//!
//! Pure read — tab switches are local view scope, no server mutation,
//! no settings flipped. End state lands on Tracking tab; reset_to_home
//! covers nothing here since there's no drawer/modal to dismiss, but
//! the helper is included for parity with other dogfood examples and
//! to absorb any incidental dev-menu state on entry.
//!
//! # Capability gap surfaced
//!
//! None planned. If a landmark fails to appear within 5 rounds × ~2.5s,
//! the final `wait_for` with 5s deadline produces a clean
//! ExpectationFailure naming the missing selector — same diagnostic
//! shape as maestro's `extendedWaitUntil` timeout.

use smix_sdk::{App, ExpectationFailure, Selector, 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 tabs navigation (v3.17 c1)");
    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 tabs_navigation_flow(&app).await {
        Ok(()) => {
            println!("\n✓ tabs navigation flow passed (1-round dogfood)");
            println!("\n🎉 v3.17 c1 dogfood — tabs_navigation ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ tabs navigation flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood tabs navigation 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/go-to-search.yaml`: repeat tap "Search" until
/// filter-chip text "People|Vehicle" is visible.
async fn go_to_search(app: &App) -> Result<(), ExpectationFailure> {
    let landmark: Selector = text_regex("People|Vehicle");
    for _ in 0..5 {
        if app
            .wait_for(&landmark, Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Search")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    app.wait_for(&landmark, Duration::from_secs(5)).await?;
    Ok(())
}

/// Mirror of `subflows/go-to-merlin.yaml`: repeat tap "Merlin" until
/// "AI Assistant" header is visible.
async fn go_to_merlin(app: &App) -> Result<(), ExpectationFailure> {
    for _ in 0..5 {
        if app
            .wait_for(&text("AI Assistant"), Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Merlin")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    app.wait_for(&text("AI Assistant"), Duration::from_secs(5))
        .await?;
    Ok(())
}

/// Mirror of `subflows/go-to-alerts.yaml`: repeat tap "Alerts" until
/// `screen-alerts` id is visible.
async fn go_to_alerts(app: &App) -> Result<(), ExpectationFailure> {
    for _ in 0..5 {
        if app
            .wait_for(&id("screen-alerts"), Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Alerts")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    app.wait_for(&id("screen-alerts"), Duration::from_secs(5))
        .await?;
    Ok(())
}

/// Mirror of `subflows/go-to-tracking.yaml`: repeat tap "Tracking" until
/// `btn-floor-plan-selector` id is visible.
async fn go_to_tracking(app: &App) -> Result<(), ExpectationFailure> {
    for _ in 0..5 {
        if app
            .wait_for(&id("btn-floor-plan-selector"), Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Tracking")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    }
    app.wait_for(&id("btn-floor-plan-selector"), Duration::from_secs(5))
        .await?;
    Ok(())
}

// ---- tabs-navigation flow (port of flows/main/tabs-navigation.yaml) ----

async fn tabs_navigation_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: go to Search → wait People|Vehicle landmark");
    go_to_search(app).await?;

    println!("step 2: go to Merlin → wait 'AI Assistant' landmark");
    go_to_merlin(app).await?;

    println!("step 3: go to Alerts → wait screen-alerts landmark");
    go_to_alerts(app).await?;

    println!("step 4: go to Tracking → wait btn-floor-plan-selector landmark");
    go_to_tracking(app).await?;

    Ok(())
}
