//! v3.13 c1 — dogfood usecase: alerts tabs (4 sub-tab simple nav).
//!
//! Port reference: `insight/tools/maestro/flows/main/alerts-tabs.yaml`.
//! Switches across the 4 Alerts sub-tabs (Events / Counting / Dwell Time
//! / Alerts) in a round-trip.
//!
//! # Why this dogfood
//!
//! Final tab-nav dogfood (v3.11 c1 search-tabs covered nested matrix;
//! v3.13 c1 covers the simpler single-level sub-tab matrix on Alerts).
//! Validates that smix text-selector tap stays composition-stable
//! against rapid sub-tab switching on a single ancestor container.
//!
//! G7 awareness: "Tracking" is not in this yaml, but "Alerts" is both
//! the bottom-tab name and the parent screen header — the yaml taps it
//! to "switch back to Alerts" sub-tab, which collides on label with
//! the bottom-tab name.
//!
//! v3.14 c1 introduces `Modifiers::ancestor` (a11y tree parent-chain
//! query). Step 6 below uses it to disambiguate sub-tab "Alerts" vs
//! bottom-tab "Alerts" — see step 6 comments for the parent-chain
//! distinguishing structure (sub-tab chain contains scrollView
//! ancestor; bottom-tab chain does not).
//!
//! # Reversibility
//!
//! Pure read — tab switching is view state.

use smix_sdk::{
    App, ExpectationFailure, Modifiers, Pattern, Role, Selector, id, role, 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 alerts tabs (v3.13 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");
    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 alerts_tabs_flow(&app).await {
        Ok(()) => {
            println!("\n✓ alerts tabs flow passed (1-round dogfood)");
            println!("\n🎉 v3.13 c1 dogfood — alerts tabs ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ alerts tabs flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood alerts tabs 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_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_secs(2)).await;
    }
    app.wait_for(&id("screen-alerts"), Duration::from_secs(5))
        .await?;
    Ok(())
}

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

async fn alerts_tabs_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: tap Alerts bottom tab → screen-alerts visible");
    go_to_alerts(app).await?;

    println!("step 2: verify all sub-tabs visible (Events / Counting / Dwell Time)");
    app.wait_for(&text("Events"), Duration::from_secs(30))
        .await?;
    app.wait_for(&text("Counting"), Duration::from_secs(5))
        .await?;
    app.wait_for(&text("Dwell Time"), Duration::from_secs(5))
        .await?;

    println!("step 3: switch to Events sub-tab");
    app.tap(&text("Events")).await?;
    tokio::time::sleep(Duration::from_millis(700)).await;

    println!("step 4: switch to Counting sub-tab");
    app.tap(&text("Counting")).await?;
    tokio::time::sleep(Duration::from_millis(700)).await;

    println!("step 5: switch to Dwell Time sub-tab");
    app.tap(&text("Dwell Time")).await?;
    tokio::time::sleep(Duration::from_millis(700)).await;

    println!(
        "step 6: tap sub-tab \"Alerts\" via Modifiers::ancestor disambiguation (v3.14 c1 cap)"
    );
    // The yaml says `tapOn: "Alerts"` to switch back to the default sub-tab.
    // "Alerts" is also the bottom-tab name on UITabBar → G7 ambiguous label.
    //
    // Tree dump (curl /tree) shows two candidates with `label="Alerts"`:
    //   - sub-tab "Alerts": parent chain contains a `scrollView` ancestor
    //                       (the horizontal sub-tab nav container);
    //                       leaf raw_type="other".
    //   - bottom-tab "Alerts": parent chain contains a `tabBar` ancestor
    //                          (UITabBar), no scrollView; leaf raw_type="button".
    //
    // `Modifiers::ancestor = role(ScrollView)` walks the candidate's
    // parent chain looking for any node whose role is ScrollView. The
    // sub-tab matches; the bottom-tab does not. v3.14 c1 cap is the
    // host-side resolver pipeline filter that performs this lookup.
    let sub_tab_alerts = Selector::Text {
        text: Pattern::text("Alerts"),
        modifiers: Modifiers {
            ancestor: Some(Box::new(role(Role::ScrollView))),
            ..Default::default()
        },
    };
    app.tap(&sub_tab_alerts).await?;
    tokio::time::sleep(Duration::from_millis(700)).await;
    // sub-tab nav stays visible; alerts screen still active.
    app.wait_for(&text("Counting"), Duration::from_secs(5))
        .await?;

    Ok(())
}
