//! v3.7 c1 — dogfood usecase: search modal reset (insight main flow).
//!
//! Port reference: `insight/tools/maestro/flows/main/search-modal.yaml`.
//! Exercises the Reset workflow on the search modal: tap a stale query
//! → `eraseText` → re-type → Reset chip → returns to Search root, then
//! reopen the modal and execute a real query submit.
//!
//! # Why this dogfood
//!
//! search-modal is the first usecase in v3.7's dogfood-driven cap-gap
//! discovery cycle (post G3 字面假设证伪, see
//! `docs/plan-history/v3.7-c1-dig.md`). It is the first flow that
//! crosses smix's `App.clear` surface (mapped from maestro `eraseText`).
//! `App.clear` is currently a raw `/clear` passthru (no selector-type
//! dispatch like `App.fill` got in v3.6 c2). If `/clear` on the runner
//! only accepts a `Text` selector (mirroring `/fill` pre-v3.6-c2), then
//! a real `clear(id("input-search"))` here surfaces a real new cap-gap
//! that the cycle should close.
//!
//! Also exercises:
//!
//! - twice-opened modal flow (open → reset → reopen → submit)
//! - regex assert after Reset (`People|Vehicle`, mirroring the maestro
//!   subflow back to the Search root)
//! - the v3.6 c2 fill selector-type dispatch in a second business surface
//!   (the input id is taken via host-resolve, the actual fill goes via
//!   `_focused_`)
//!
//! # Reversibility
//!
//! Pure read — search queries are transient. Closing the modal returns
//! to the Search screen, which sits behind a bottom tab.

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 search modal reset (v3.7 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!("foregrounding {bundle_id}");
    app.foreground(&bundle_id).await?;
    tokio::time::sleep(Duration::from_secs(2)).await;

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

    println!("reset_to_home: tap Device tab + drawer-close");
    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 search_modal_flow(&app).await {
        Ok(()) => {
            println!("\n✓ search modal flow passed (1-round dogfood)");
            println!("\n🎉 v3.7 c1 dogfood — search modal reset ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ search modal flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood search modal FAIL".into())
        }
    }
}

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

async fn ensure_login(app: &App) -> Result<(), ExpectationFailure> {
    // Check both the login screen text AND the dev-bubble id. The login
    // screen flashes briefly on RN bundle re-init even when AsyncStorage
    // has cached auth — see "Log in to Insight" being found by /find for
    // a single tick while the home screen is still mounting. Insist on
    // the dev-bubble before walking the login flow; if it's gone, the
    // session is 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;
    }
    // Home-screen ready indicator. v3.5+ baseline used `text("Open menu")`
    // (the drawer hamburger's accessibilityLabel). Insight RN bundle has since
    // dropped that label on some screens (e.g. Merlin tab's header lacks it),
    // so fall back to any of the bottom-tab labels — at least one is always
    // visible on a home tab.
    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(())
}

async fn go_to_search(app: &App) -> Result<(), ExpectationFailure> {
    for _ in 0..5 {
        if app
            .wait_for(&text_regex("People|Vehicle"), Duration::from_millis(500))
            .await
            .is_ok()
        {
            return Ok(());
        }
        let _ = app.tap(&text("Search")).await;
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    app.wait_for(&text_regex("People|Vehicle"), Duration::from_secs(5))
        .await?;
    Ok(())
}

// ---- search-modal flow (port of flows/main/search-modal.yaml) -----------

async fn search_modal_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: tap Search bottom tab → People/Vehicle sub-tabs visible");
    go_to_search(app).await?;

    println!("step 2: open search modal (id btn-search-open)");
    app.tap(&id("btn-search-open")).await?;

    println!("step 3: wait for input field (id input-search, ≤30s)");
    app.wait_for(&id("input-search"), Duration::from_secs(30))
        .await?;

    println!("step 4: tap input field to focus");
    app.tap(&id("input-search")).await?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    println!("step 5: erase any prior text (App.clear, v3.7 c1 surface)");
    app.clear(&id("input-search")).await?;
    tokio::time::sleep(Duration::from_millis(200)).await;

    println!("step 6: fill \"test query\" via chunked fill");
    app.fill(&id("input-search"), "test query").await?;
    tokio::time::sleep(Duration::from_millis(400)).await;

    println!("step 7: assert Reset chip visible (≤5s)");
    app.wait_for(&text("Reset"), Duration::from_secs(5)).await?;

    println!("step 8: tap Reset");
    app.tap(&text("Reset")).await?;
    tokio::time::sleep(Duration::from_millis(600)).await;

    println!("step 9: returned to Search root (People|Vehicle visible, ≤5s)");
    app.wait_for(&text_regex("People|Vehicle"), Duration::from_secs(5))
        .await?;

    println!("step 10: reopen search modal (id btn-search-open)");
    app.tap(&id("btn-search-open")).await?;

    println!("step 11: wait for input field again (id input-search, ≤30s)");
    app.wait_for(&id("input-search"), Duration::from_secs(30))
        .await?;

    println!("step 12: tap input field to focus");
    app.tap(&id("input-search")).await?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    println!("step 13: erase again (App.clear)");
    app.clear(&id("input-search")).await?;
    tokio::time::sleep(Duration::from_millis(200)).await;

    println!("step 14: fill \"hello\" via chunked fill");
    app.fill(&id("input-search"), "hello").await?;
    tokio::time::sleep(Duration::from_millis(400)).await;

    println!("step 15: tap submit (id btn-search-submit)");
    app.tap(&id("btn-search-submit")).await?;
    tokio::time::sleep(Duration::from_millis(600)).await;

    Ok(())
}
