//! v3.8 c1 — dogfood usecase: video player + fullscreen + transport controls.
//!
//! Port reference: `insight/tools/maestro/flows/main/player-controls.yaml`
//! & `insight/tools/maestro/subflows/open-device-detail.yaml`. Drives a
//! video-bearing device-detail panel through:
//!
//! 1. fullscreen toggle (enter + exit)
//! 2. Playback mode switcher (text-selector tap, optional)
//! 3. transport controls (locate / play-pause, all optional)
//!
//! # Why this dogfood
//!
//! First dogfood that touches the AVKit-resident video pipeline. Every
//! prior dogfood (lang switch / device detail / Merlin / search-vehicle
//! / search-modal / search-person / manage-devices) stayed on RN /
//! drawer / list surfaces; nothing exercised the embedded video player,
//! its fullscreen overlay, or the transport-control chrome that lives
//! beneath it. If the resolver / fill / tap pipeline has a sim-only
//! limit around AVKit-rendered controls, this flow surfaces it.
//!
//! Also exercises:
//!
//! - id selectors taken via c2 host-resolve fallback (every transport
//!   control is an id)
//! - Apple AVKit overlay vs RN tree disambiguation (fullscreen toggle
//!   re-uses the same id but may re-mount under a different ancestor)
//! - optional-fallback pattern (transport controls don't always render
//!   on cold launch — same shape as v3.7 c2 spatial-row probe)
//!
//! # Reversibility
//!
//! Pure read — all controls (fullscreen, play/pause, locate) are
//! transient UI state, no backend mutation. Exits cleanly back to the
//! device-detail panel.

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 player controls (v3.8 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 player_controls_flow(&app).await {
        Ok(()) => {
            println!("\n✓ player controls flow passed (1-round dogfood)");
            println!("\n🎉 v3.8 c1 dogfood — player controls ✅");
            Ok(())
        }
        Err(e) => {
            println!("\n✗ player controls flow failed");
            for line in e.to_prompt().lines() {
                println!("    {line}");
            }
            Err("dogfood player controls 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`. Three id-selector tap+wait,
/// same shape as v3.5 c5 dogfood usecase.
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(())
}

// ---- player-controls flow (port of flows/main/player-controls.yaml) -----

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

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

    println!("step 3: enter fullscreen (tap btn-player-fullscreen)");
    app.tap(&id("btn-player-fullscreen")).await?;
    tokio::time::sleep(Duration::from_millis(1200)).await;

    println!("step 4: verify still in app (btn-player-fullscreen re-visible in fullscreen, ≤5s)");
    app.wait_for(&id("btn-player-fullscreen"), Duration::from_secs(5))
        .await?;

    println!("step 5: exit fullscreen (tap btn-player-fullscreen)");
    app.tap(&id("btn-player-fullscreen")).await?;
    tokio::time::sleep(Duration::from_millis(1200)).await;

    println!("step 6: verify returned to portrait (panel-device-detail visible, ≤30s)");
    app.wait_for(&id("panel-device-detail"), Duration::from_secs(30))
        .await?;

    println!("step 7: switch to Playback mode if mode switcher present (optional)");
    if app.find(&text("Playback")).await? {
        let _ = app.tap(&text("Playback")).await;
        tokio::time::sleep(Duration::from_millis(800)).await;
    } else {
        println!("  no Playback switcher visible (live-only mode)");
    }

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

    println!("step 9: tap locate to surface transport controls");
    app.tap(&id("btn-player-locate")).await?;
    tokio::time::sleep(Duration::from_millis(800)).await;

    println!("step 10: probe play button (id btn-player-play, ≤5s, optional)");
    let play_visible = app
        .wait_for(&id("btn-player-play"), Duration::from_secs(5))
        .await
        .is_ok();
    if play_visible {
        println!("  play button visible, tapping it");
        let _ = app.tap(&id("btn-player-play")).await;
        tokio::time::sleep(Duration::from_millis(600)).await;
    } else {
        println!("  play button not visible (transport not rendered or sim limit)");
    }

    Ok(())
}
