use super::{build_pipeline_desc, ensure_remote_usb_audio_ready};
use temp_env::with_vars;
use tempfile::tempdir;

#[test]
fn speaker_downlink_pipeline_keeps_aac_adts_transport_and_level_probe() {
    let _ = super::gst::init();
    let result = build_pipeline_desc("hw:Loopback,0");
    match result {
        Ok(desc) => {
            assert!(desc.contains("alsasrc device=\"hw:Loopback,0\""));
            assert!(desc.contains("audio/x-raw,format=S16LE,channels=2,rate=48000"));
            assert!(desc.contains("aacparse"));
            assert!(desc.contains("stream-format=adts"));
            assert!(desc.contains("level name=source_level"));
            assert!(desc.contains("appsink name=asink"));
        }
        Err(err) => {
            assert!(
                err.to_string().contains("no AAC encoder plugin available"),
                "unexpected build failure: {err:#}"
            );
        }
    }
}

#[test]
fn remote_usb_audio_reports_not_attached_gadget() {
    let dir = tempdir().expect("tempdir");
    let cfg_root = dir.path().join("cfg");
    let sys_root = dir.path().join("sys");
    let udc_dir = sys_root.join("class/udc/fake-ctrl.usb");
    std::fs::create_dir_all(cfg_root.join("lesavka")).expect("cfg");
    std::fs::create_dir_all(&udc_dir).expect("udc");
    std::fs::write(cfg_root.join("lesavka/UDC"), "fake-ctrl.usb\n").expect("udc file");
    std::fs::write(udc_dir.join("state"), "not attached\n").expect("state");

    with_vars(
        [
            (
                "LESAVKA_GADGET_CONFIGFS_ROOT",
                Some(cfg_root.to_string_lossy().to_string()),
            ),
            (
                "LESAVKA_GADGET_SYSFS_ROOT",
                Some(sys_root.to_string_lossy().to_string()),
            ),
        ],
        || {
            let err = ensure_remote_usb_audio_ready("hw:UAC2Gadget,0")
                .expect_err("not attached gadget should block remote speaker audio");
            assert!(
                err.to_string()
                    .contains("remote USB gadget is not attached")
            );
        },
    );
}

#[test]
fn remote_usb_audio_allows_non_gadget_override() {
    ensure_remote_usb_audio_ready("hw:Loopback,0").expect("non-gadget override");
}
