//! v3.10 c1 — dogfood usecase: device video setting (settings modal path).
//!
//! Port reference: `insight/tools/maestro/flows/main/device-video-setting.yaml`.
//! Drives the device playback view → btn-video-quality → Camera Settings
//! modal, then asserts the four quality-option labels (SD / HD / HDR
//! Mode / Night Mode).
//!
//! # Why this dogfood
//!
//! First settings-form dogfood. v3.5-v3.9 累计 12 dogfood 全聚焦 nav /
//! modal / input / playback / spatial+index / text-regex+nth / clear
//! dispatch / multi-stage 路径 — settings form (Camera Settings) 路径在
//! 业务侧尚未 cover. This validates the resolver against a RN-rendered
//! settings popup with four sibling option labels (all text-selector).
//!
//! port adaptive: the yaml assumes the app is already on a playback view
//! when it starts (btn-video-quality is a playback-control icon). The
//! actual cold-launch state on this build is dashboard / device list, so
//! we run `open_device_detail` first (same subflow as v3.5 c5 / v3.8 c1)
//! to land on a playback view before probing for btn-video-quality.
//!
//! Also exercises:
//!
//! - btn-video-quality id-selector tap (host-resolve + tap fallback)
//! - modal subtree filter (v3.5 c1 topmost_modal_filter against the
//!   Camera Settings popup; the four labels live inside the modal)
//!
//! # Reversibility
//!
//! Pure read — Camera Settings modal only asserts visibility, no toggle
//! mutation. Closing the modal (or backgrounding the app) returns to a
//! clean state.

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 device video setting (v3.10 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 device_video_setting_flow(&app).await {
        Ok(()) => {
            println!("\n✓ device video setting flow passed (1-round dogfood)");
            println!("\n🎉 v3.10 c1 dogfood — device video setting ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ device video setting flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood device video setting 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(())
}

/// Subflow port of `open-device-detail.yaml`. Same shape as v3.5 c5 +
/// v3.8 c1 — three id-selector tap+wait to land on playback view.
async fn open_device_detail(app: &App) -> Result<(), ExpectationFailure> {
    println!("  wait device list (id btn-device-search, ≤30s)");
    app.wait_for(&id("btn-device-search"), Duration::from_secs(30))
        .await?;
    println!("  wait Detail button visible (id btn-device-detail, ≤15s)");
    app.wait_for(&id("btn-device-detail"), Duration::from_secs(15))
        .await?;
    println!("  tap Detail (id btn-device-detail)");
    app.tap(&id("btn-device-detail")).await?;
    println!("  wait device detail panel (id panel-device-detail, ≤30s)");
    app.wait_for(&id("panel-device-detail"), Duration::from_secs(30))
        .await?;
    Ok(())
}

// ---- device-video-setting flow (port of flows/main/device-video-setting.yaml) ----

async fn device_video_setting_flow(app: &App) -> Result<(), ExpectationFailure> {
    println!("step 1: open device detail (subflow → playback view)");
    open_device_detail(app).await?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    println!("step 2: wait for video quality button (id btn-video-quality, ≤30s)");
    app.wait_for(&id("btn-video-quality"), Duration::from_secs(30))
        .await?;

    println!("step 3: tap btn-video-quality to open Camera Settings modal");
    app.tap(&id("btn-video-quality")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 4: wait Camera Settings header (≤30s)");
    app.wait_for(&text("Camera Settings"), Duration::from_secs(30))
        .await?;

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

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

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

    println!("step 8: assert Night Mode visible (≤5s)");
    app.wait_for(&text("Night Mode"), Duration::from_secs(5))
        .await?;

    Ok(())
}
