xybrid-sdk 0.1.1

Developer-facing API for hybrid cloud-edge AI inference: load/run/stream models with declarative routing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
// Allow dead code in alpha crate — many modules are scaffolded but not yet wired up.
#![allow(dead_code)]
#![allow(
    clippy::too_many_arguments,
    clippy::ptr_arg,
    clippy::map_identity,
    clippy::while_let_loop
)]

//! Xybrid SDK - Developer-facing API for hybrid cloud-edge AI inference.
//!
//! This crate provides high-level abstractions for:
//! - Loading and running ML models (ASR, TTS, embeddings)
//! - Streaming inference for real-time applications
//! - Multi-stage pipelines with intelligent routing
//!
//! # Architecture
//!
//! The SDK follows a **Loader → Model → Run** pattern:
//!
//! ```text
//! ModelLoader::from_registry()  →  loader.load()  →  model.run(&envelope)
//!                                                 →  model.stream(config)
//! ```
//!
//! # Quick Start
//!
//! ## Initialization
//!
//! Anonymous use works out of the box — every inference path runs locally.
//! Provide an API key to light up the platform dashboard:
//!
//! ```no_run
//! // Anonymous — local inference, telemetry disabled
//! xybrid_sdk::init().run();
//!
//! // Authenticated — telemetry exporter starts automatically
//! xybrid_sdk::init()
//!     .api_key("xy_live_...")
//!     .run();
//! ```
//!
//! Get a free key at <https://dashboard.xybrid.dev>. The first inference
//! call without a key emits a one-shot info log nudging the developer
//! toward the dashboard; set `XYBRID_QUIET=1` to suppress it.
//!
//! ## Batch Inference
//!
//! ```no_run
//! # fn _example() -> Result<(), Box<dyn std::error::Error>> {
//! use xybrid_sdk::ModelLoader;
//! use xybrid_sdk::ir::{Envelope, EnvelopeKind};
//!
//! // Load model from registry
//! let loader = ModelLoader::from_registry("whisper-tiny");
//! let model = loader.load()?;
//!
//! // Run inference
//! let audio_bytes: Vec<u8> = vec![];
//! let envelope = Envelope::new(EnvelopeKind::Audio(audio_bytes));
//! let result = model.run(&envelope, None)?;
//! println!("Transcription: {}", result.unwrap_text());
//! # Ok(())
//! # }
//! ```
//!
//! ## Streaming ASR
//!
//! ```no_run
//! # fn _example() -> Result<(), Box<dyn std::error::Error>> {
//! use xybrid_sdk::{ModelLoader, StreamConfig};
//!
//! let model = ModelLoader::from_directory("/path/to/whisper-model")?.load()?;
//! let stream = model.stream(StreamConfig::with_vad())?;
//!
//! // Feed audio chunks
//! let audio_samples: Vec<f32> = vec![];
//! stream.feed(&audio_samples)?;
//!
//! // Get final transcript
//! let result = stream.flush()?;
//! println!("Transcript: {}", result.text);
//! # Ok(())
//! # }
//! ```
//!
//! ## Pipelines
//!
//! ```no_run
//! # fn _example() -> Result<(), Box<dyn std::error::Error>> {
//! use xybrid_sdk::run_pipeline;
//!
//! let result = run_pipeline("examples/pipeline.yaml")?;
//! println!("Pipeline completed in {}ms", result.total_latency_ms);
//! for stage in &result.stages {
//!     println!("  {}: {}ms ({})", stage.name, stage.latency_ms, stage.target);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Model Warmup (for LLM and other large models)
//!
//! Pre-load models at app startup for fast first inference:
//!
//! ```no_run
//! # fn _example() -> Result<(), Box<dyn std::error::Error>> {
//! use xybrid_sdk::{ModelLoader, PipelineRef};
//! use xybrid_sdk::ir::{Envelope, EnvelopeKind};
//!
//! // Option 1: Warmup a single model
//! let loader = ModelLoader::from_registry("gemma-3-1b");
//! let model = loader.load()?;
//! model.warmup()?;  // Pre-loads model weights, compiles shaders
//! let envelope = Envelope::new(EnvelopeKind::Text("Hello".into()));
//! let result = model.run(&envelope, None)?;  // Fast!
//!
//! // Option 2: Warmup a pipeline
//! let yaml = "stages: []";
//! let pipeline = PipelineRef::from_yaml(yaml)?.load()?;
//! pipeline.load_models()?;  // Download models
//! pipeline.warmup()?;       // Pre-load into memory
//! let result = pipeline.run(&envelope)?;  // Fast!
//!
//! // Option 3: Async warmup for background loading
//! let model = loader.load()?;
//! tokio::spawn(async move {
//!     model.warmup_async().await
//! });
//! # Ok(())
//! # }
//! ```

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use tokio::sync::mpsc;
use xybrid_core::context::{DeviceMetrics, StageDescriptor};
use xybrid_core::ir::{Envelope, EnvelopeKind};
use xybrid_core::orchestrator::routing_engine::LocalAvailability;
use xybrid_core::orchestrator::{Orchestrator, StageExecutionResult};

// ============================================================================
// Module Declarations
// ============================================================================

pub mod benchmark;
pub mod cache;
pub mod device;
pub mod llm;
pub mod metadata_gen;
pub mod model;
pub mod pipeline;
pub mod platform;
pub mod registry_client;
pub mod result;
pub mod run_options;
pub mod source;
pub mod stream;
pub mod streaming;
pub mod telemetry;
pub mod telemetry_optout;

// ============================================================================
// Re-exports
// ============================================================================

// Re-export xybrid_core modules (selective to avoid conflicts)
pub use xybrid_core::bundler;
pub use xybrid_core::cache_provider::CacheProvider;
pub use xybrid_core::context;
pub use xybrid_core::conversation::ConversationContext;
pub use xybrid_core::device::{
    clear_battery_level, clear_thermal_state, set_battery_level, set_thermal_state, DeviceProfile,
    MemoryPressure, ResourceMonitor, ResourceSnapshot, ResourceTelemetryMode, ResourceUsageSummary,
    RunGuard as ResourceRunGuard, ThermalState,
};
pub use xybrid_core::execution;
pub use xybrid_core::features;
pub use xybrid_core::ir;
pub use xybrid_core::orchestrator;
pub use xybrid_core::orchestrator::routing_engine;

// Re-export voice types for TTS model discovery
pub use xybrid_core::execution::{VoiceConfig, VoiceInfo};

// Re-export streaming and generation types for LLM inference (always available for FFI/bindings)
pub use xybrid_core::runtime_adapter::types::{
    GenerationConfig, PartialToken, StreamingCallback, StreamingError,
};

// Backwards compatibility re-exports
#[doc(hidden)]
pub use xybrid_core::execution as template_executor;
#[doc(hidden)]
pub use xybrid_core::execution::template as execution_template;

// SDK types (new API)
pub use benchmark::{compare_benchmarks, BenchmarkResult, ExecutionProviderInfo};
pub use cache::{CacheManager, CacheStatus, SdkCacheProvider};
pub use device::{device_id, Device};
pub use llm::{
    default_gateway_url, set_gateway_url, ChatMessage, CompletionRequest, CompletionResponse,
    LlmBackend, LlmClientConfig, MessageRole, TokenUsage,
};
pub use model::SdkError;
pub use model::{
    ModelLoader, SdkResult, SeamInfo, StreamConfig, StreamEvent, StreamToken, XybridModel,
};
pub use platform::current_platform;
pub use registry_client::{CacheStats, ModelSummary, RegistryClient, ResolvedVariant};
pub use run_options::{AbortPolicy, AbortReason, AbortSignal, CancellationToken, RunOptions};
// Re-exported so callers can use the trait form of `SdkError::is_retryable`
// / `retry_after` (e.g. in generic retry helpers) without naming
// `xybrid_core`. The inherent methods on `SdkError` cover the common case
// without any import.
pub use xybrid_core::http::RetryableError;
// Pipeline API (PipelineRef → Pipeline)
pub use pipeline::{
    // Config types for FFI bindings (Flutter, Kotlin, Swift)
    AudioInputConfig,
    AudioSampleFormat,
    ConfigOutputType,
    DownloadProgress,
    // FFI result types for platform bindings (Flutter, Kotlin, Swift)
    FfiPipelineExecutionResult,
    FfiStageExecutionResult,
    InputConfig,
    InputType,
    Pipeline,
    PipelineExecutionResult,
    PipelineInputType,
    PipelineRef,
    PipelineSource,
    StageInfo,
    StageStatus,
    StageTarget,
    StageTiming as PipelineStageTiming, // Alias to avoid conflict with legacy StageTiming
    TextInputConfig,
    Xybrid,
};
pub use result::{InferenceMetrics, InferenceResult, OutputType, StageLatency};
pub use source::ModelSource;
pub use stream::{PartialResult, StreamState, StreamStats, TranscriptionResult, XybridStream};
// FFI streaming types for platform bindings (Flutter, Kotlin, Swift)
pub use streaming::{FfiPartialResult, FfiStreamState, FfiStreamStats, FfiStreamingConfig};
pub use telemetry::{
    // Orchestrator event bridge
    bridge_orchestrator_events,
    convert_orchestrator_event,
    flush_platform_telemetry,
    init_platform_telemetry,
    init_platform_telemetry_from_env,
    publish_telemetry_event,
    register_telemetry_sender,
    set_telemetry_pipeline_context,
    shutdown_platform_telemetry,
    // Platform telemetry exports
    subscribe_orchestrator_events,
    BridgeError,
    BridgeHandle,
    HttpTelemetryExporter,
    OrchestratorEventBridge,
    TelemetryConfig,
    TelemetryEvent,
    TelemetrySender,
};
pub use telemetry_optout::is_telemetry_opted_out;

/// Re-export OrchestratorEvent for event subscriptions
pub use xybrid_core::event_bus::OrchestratorEvent;

/// Re-export execution listener types for custom instrumentation
pub use xybrid_core::execution::listener::{
    clear_execution_listener, set_execution_listener, ExecutionEvent,
};

// ============================================================================
// SDK Configuration
// ============================================================================

use std::sync::OnceLock;

/// Global SDK configuration.
static SDK_CONFIG: OnceLock<SdkConfig> = OnceLock::new();

/// Process-global binding identifier set by platform bindings at init.
///
/// First-set-wins (backed by [`OnceLock`]); after the first
/// [`set_binding`] call, subsequent calls are silent no-ops. Read via
/// [`get_binding`], which returns [`DEFAULT_BINDING`] when unset.
static BINDING: OnceLock<&'static str> = OnceLock::new();

/// Default binding identifier reported in the registry telemetry header.
///
/// Each platform binding (Flutter, Kotlin, Swift, Unity) overrides this via
/// [`set_binding`] (process-global) or [`SdkConfig::with_binding`] (per-config)
/// so registry calls can be attributed correctly.
pub const DEFAULT_BINDING: &str = "rust";

/// SDK crate version, stamped onto every telemetry event as `sdk_version` and
/// used in the `X-Xybrid-Client` registry header.
///
/// Sourced from `CARGO_PKG_VERSION` at compile time so the value tracks the
/// `xybrid-sdk` crate's own `Cargo.toml` without manual sync. The `xybrid-core`
/// version is exposed separately as [`xybrid_core::VERSION`]; the two can
/// diverge across releases.
pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Register the binding identifier for this process.
///
/// Each platform binding (Flutter, Kotlin, Swift, Unity) calls this once at
/// SDK init. The first call wins — subsequent calls are silent no-ops, which
/// matches the lifecycle (a process is bound to exactly one platform binding).
///
/// `RegistryClient` default constructors (`new`, `default_client`,
/// `with_url`, `from_env`) read this value via [`get_binding`], so any
/// `RegistryClient` constructed after [`set_binding`] reports the configured
/// binding in the `X-Xybrid-Client` header without explicit threading.
pub fn set_binding(binding: &'static str) {
    let _ = BINDING.set(binding);
}

/// Read the process-global binding identifier.
///
/// Returns the value passed to the most recent successful [`set_binding`]
/// call, falling back to [`DEFAULT_BINDING`] when unset.
pub fn get_binding() -> &'static str {
    BINDING.get().copied().unwrap_or(DEFAULT_BINDING)
}

/// SDK configuration options.
#[derive(Debug, Clone, Default)]
pub struct SdkConfig {
    /// Custom cache directory (required on Android, optional elsewhere)
    pub cache_dir: Option<std::path::PathBuf>,
    /// Binding identifier reported in the `X-Xybrid-Client` registry header.
    ///
    /// Defaults to [`DEFAULT_BINDING`] when unset. Bindings should set this
    /// at SDK init via [`SdkConfig::with_binding`].
    pub binding: Option<&'static str>,
}

impl SdkConfig {
    /// Override the binding identifier reported in the registry telemetry header.
    ///
    /// Returns `self` to support a fluent builder style.
    pub fn with_binding(mut self, binding: &'static str) -> Self {
        self.binding = Some(binding);
        self
    }

    /// Resolve the configured binding identifier, falling back to [`DEFAULT_BINDING`].
    pub fn binding(&self) -> &'static str {
        self.binding.unwrap_or(DEFAULT_BINDING)
    }
}

/// Initialize the SDK with a custom cache directory.
///
/// **IMPORTANT**: On Android, this MUST be called before any model loading operations.
/// The cache directory should be obtained from Flutter's `path_provider` package
/// (e.g., `getApplicationDocumentsDirectory()`).
///
/// On other platforms (iOS, macOS, Linux, Windows), this is optional - the SDK
/// will use platform-specific default directories if not configured.
///
/// This function also sets environment variables (`HOME`, `HF_HOME`) to ensure
/// that third-party libraries (like mistralrs/hf-hub) can find cache directories
/// on platforms like Android where standard Unix paths don't exist.
///
/// # Example (Flutter/Dart)
///
/// ```dart
/// import 'package:path_provider/path_provider.dart';
///
/// Future<void> initXybrid() async {
///   final appDir = await getApplicationDocumentsDirectory();
///   final cacheDir = '${appDir.path}/xybrid/models';
///   initSdkCacheDir(cacheDir);
/// }
/// ```
///
/// # Arguments
///
/// * `cache_dir` - Path to the directory where model bundles will be cached
pub fn init_sdk_cache_dir(cache_dir: impl Into<std::path::PathBuf>) {
    let cache_path = cache_dir.into();

    // Set environment variables for third-party libraries (hf-hub, mistralrs, etc.)
    // On Android, dirs::home_dir() and dirs::cache_dir() return None, causing panics.
    // Setting these env vars provides fallback paths for those libraries.
    if let Some(cache_str) = cache_path.to_str() {
        // Set HOME if not already set (used by dirs::home_dir() fallback)
        if std::env::var("HOME").is_err() {
            // Use parent of cache dir as HOME
            if let Some(parent) = cache_path.parent() {
                if let Some(parent_str) = parent.to_str() {
                    std::env::set_var("HOME", parent_str);
                }
            }
        }

        // Set HF_HOME for hf-hub/mistralrs (used for model tokenizer/config caching)
        // This takes priority over XDG_CACHE_HOME
        let hf_cache = cache_path.join("huggingface");
        if let Some(hf_str) = hf_cache.to_str() {
            std::env::set_var("HF_HOME", hf_str);
        }

        // Set HF_HUB_OFFLINE to prevent any download attempts
        // We bundle all required files, so hf-hub should never need to fetch anything
        std::env::set_var("HF_HUB_OFFLINE", "1");

        // Also set XDG_CACHE_HOME as a fallback for other XDG-compliant libraries
        if std::env::var("XDG_CACHE_HOME").is_err() {
            std::env::set_var("XDG_CACHE_HOME", cache_str);
        }
    }

    let config = SdkConfig {
        cache_dir: Some(cache_path),
        ..SdkConfig::default()
    };
    let _ = SDK_CONFIG.set(config);
}

/// Get the configured cache directory (if set).
pub fn get_sdk_cache_dir() -> Option<std::path::PathBuf> {
    SDK_CONFIG.get().and_then(|c| c.cache_dir.clone())
}

/// Check if the SDK cache directory has been configured.
pub fn is_sdk_cache_configured() -> bool {
    SDK_CONFIG
        .get()
        .and_then(|c| c.cache_dir.as_ref())
        .is_some()
}

/// Set the Xybrid API key for gateway authentication.
///
/// This sets the `XYBRID_API_KEY` environment variable which is used
/// by the LLM client when routing through the Xybrid Gateway.
///
/// # Example
///
/// ```rust
/// use xybrid_sdk::set_api_key;
///
/// // Set API key at startup
/// set_api_key("your-xybrid-api-key");
///
/// // Now pipelines will use this key for gateway requests
/// ```
///
/// # Note
///
/// For Flutter apps, you can also set this from Dart before running pipelines.
/// The key is stored in the process environment and persists for the app lifetime.
pub fn set_api_key(api_key: &str) {
    std::env::set_var("XYBRID_API_KEY", api_key);
}

/// Set a provider-specific API key for direct API calls.
///
/// Use this when running LLM stages with `backend: "direct"` in the pipeline.
///
/// # Supported Providers
///
/// - `"openai"` → Sets `OPENAI_API_KEY`
/// - `"anthropic"` → Sets `ANTHROPIC_API_KEY`
/// - `"google"` → Sets `GOOGLE_API_KEY`
/// - `"openrouter"` → Sets `OPENROUTER_API_KEY`
/// - `"elevenlabs"` → Sets `ELEVENLABS_API_KEY`
///
/// # Example
///
/// ```rust
/// use xybrid_sdk::set_provider_api_key;
///
/// // For direct OpenAI API calls
/// set_provider_api_key("openai", "sk-...");
/// ```
pub fn set_provider_api_key(provider: &str, api_key: &str) {
    let env_var = match provider.to_lowercase().as_str() {
        "openai" => "OPENAI_API_KEY",
        "anthropic" | "claude" => "ANTHROPIC_API_KEY",
        "google" | "gemini" => "GOOGLE_API_KEY",
        "openrouter" => "OPENROUTER_API_KEY",
        "elevenlabs" => "ELEVENLABS_API_KEY",
        _ => {
            // Custom provider - use uppercase with _API_KEY suffix
            let custom_var = format!("{}_API_KEY", provider.to_uppercase());
            std::env::set_var(&custom_var, api_key);
            return;
        }
    };
    std::env::set_var(env_var, api_key);
}

/// Get the currently configured Xybrid API key (if set).
///
/// Returns `None` if no API key is configured.
pub fn get_api_key() -> Option<String> {
    std::env::var("XYBRID_API_KEY").ok()
}

/// Check if the Xybrid API key is configured.
pub fn has_api_key() -> bool {
    std::env::var("XYBRID_API_KEY").is_ok()
}

// ============================================================================
// XybridInit — one-stop builder for SDK initialization
// ============================================================================

/// Start configuring the SDK. Call `.run()` to apply.
///
/// See [`XybridInit`] for the full builder surface.
pub fn init() -> XybridInit {
    XybridInit::default()
}

/// Builder that bundles SDK initialization into a single call.
///
/// Replaces the older multi-step setup (`init_sdk_cache_dir` →
/// `set_api_key` → `init_platform_telemetry`) for host apps that want one
/// entry point. The legacy free functions stay public for callers that
/// need finer control.
///
/// # Anonymous use
///
/// Omitting [`api_key`](Self::api_key) is supported: every inference path
/// still runs locally. The platform telemetry exporter is not started, and
/// the first inference logs a one-shot info-level hint pointing at the
/// dashboard. Set `XYBRID_QUIET=1` to suppress the hint.
///
/// # Examples
///
/// Anonymous, default cache directory:
///
/// ```no_run
/// xybrid_sdk::init().run();
/// ```
///
/// Authenticated; telemetry defaults to the production ingest URL:
///
/// ```no_run
/// xybrid_sdk::init()
///     .api_key("xy_live_...")
///     .run();
/// ```
///
/// Full configuration — self-hosted dashboard with resource sampling on:
///
/// ```no_run
/// use xybrid_sdk::ResourceTelemetryMode;
///
/// xybrid_sdk::init()
///     .api_key("xy_live_...")
///     .ingest_url("http://192.168.1.78:8081")
///     .resource_telemetry(ResourceTelemetryMode::Summary { interval_ms: 5000 })
///     .run();
/// ```
#[derive(Debug, Clone, Default)]
#[must_use = "call .run() to apply the configuration"]
pub struct XybridInit {
    api_key: Option<String>,
    cache_dir: Option<std::path::PathBuf>,
    gateway_url: Option<String>,
    ingest_url: Option<String>,
    resource_telemetry: Option<xybrid_core::device::ResourceTelemetryMode>,
    binding: Option<&'static str>,
}

impl XybridInit {
    /// Set the Xybrid API key. With a key, the platform telemetry exporter
    /// starts on `.run()` and inference traces flow to the dashboard.
    ///
    /// Skip this call to run anonymously.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Override the model cache directory. Required on Android (where
    /// `dirs::cache_dir()` returns `None`); optional elsewhere.
    pub fn cache_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
        self.cache_dir = Some(dir.into());
        self
    }

    /// Override the LLM gateway URL. Defaults to the production gateway
    /// or to `XYBRID_GATEWAY_URL` / `XYBRID_PLATFORM_URL` if set.
    pub fn gateway_url(mut self, url: impl Into<String>) -> Self {
        self.gateway_url = Some(url.into());
        self
    }

    /// Override the telemetry ingest URL. Defaults to
    /// [`telemetry::DEFAULT_INGEST_URL`] when an API key is set. Use this
    /// for self-hosted dashboards or on-device dev consoles.
    pub fn ingest_url(mut self, url: impl Into<String>) -> Self {
        self.ingest_url = Some(url.into());
        self
    }

    /// Configure resource-telemetry sampling. Defaults to `Off`.
    pub fn resource_telemetry(mut self, mode: xybrid_core::device::ResourceTelemetryMode) -> Self {
        self.resource_telemetry = Some(mode);
        self
    }

    /// Register the binding identifier for this process (e.g. `"flutter"`,
    /// `"kotlin"`, `"swift"`, `"unity"`). Bindings call this; host apps
    /// rarely need to.
    pub fn binding(mut self, binding: &'static str) -> Self {
        self.binding = Some(binding);
        self
    }

    /// Apply the configuration. Cache dir, gateway URL, API key, and
    /// telemetry exporter are wired up in the order other code in the SDK
    /// expects them.
    ///
    /// Idempotent for the cache dir and binding (first-set-wins via
    /// `OnceLock`). The telemetry exporter has its own process-wide
    /// once-guard at the binding layer; a second `.run()` does not spawn a
    /// second exporter.
    pub fn run(self) {
        if let Some(binding) = self.binding {
            set_binding(binding);
        }
        if let Some(dir) = self.cache_dir {
            init_sdk_cache_dir(dir);
        }
        if let Some(url) = self.gateway_url.as_deref() {
            set_gateway_url(url);
        }
        if let Some(key) = self.api_key.as_deref() {
            set_api_key(key);
        }

        if let Some(key) = self.api_key.as_deref() {
            let endpoint = self
                .ingest_url
                .as_deref()
                .unwrap_or(telemetry::DEFAULT_INGEST_URL);
            let mut config = telemetry::TelemetryConfig::new(endpoint, key);
            if let Some(mode) = self.resource_telemetry {
                config = config.with_resource_telemetry(mode);
            }
            telemetry::init_platform_telemetry(config);
        } else if self.ingest_url.is_some() {
            log::warn!(
                target: "xybrid_sdk",
                "ingest_url set without api_key; telemetry exporter not started"
            );
        }
    }
}

/// Re-export common types for convenience
pub mod prelude {
    pub use xybrid_core::context::{DeviceMetrics, StageDescriptor};
    pub use xybrid_core::ir::{Envelope, EnvelopeKind};
    pub use xybrid_core::orchestrator::routing_engine::{
        LocalAvailability, RouteTarget, RoutingDecision,
    };
    pub use xybrid_core::orchestrator::{Orchestrator, OrchestratorError, StageExecutionResult};
}

/// Async event stream for subscribing to orchestrator events.
pub struct EventStream {
    receiver: mpsc::Receiver<OrchestratorEvent>,
}

impl EventStream {
    /// Receive the next event asynchronously.
    pub async fn recv(&mut self) -> Option<OrchestratorEvent> {
        self.receiver.recv().await
    }

    /// Try to receive an event without blocking.
    pub fn try_recv(&mut self) -> Result<OrchestratorEvent, mpsc::error::TryRecvError> {
        self.receiver.try_recv()
    }
}

/// Create an async event stream from an orchestrator's event bus.
pub fn subscribe_events(orchestrator: &Orchestrator) -> EventStream {
    let (tx, rx) = mpsc::channel(100);
    let event_bus = orchestrator.event_bus();
    let subscription = event_bus.subscribe();

    // Bridge sync receiver to async channel using a dedicated thread
    // The subscription receiver is not Send, so we use a blocking thread
    std::thread::spawn(move || {
        loop {
            match subscription.recv() {
                Ok(event) => {
                    // Use blocking_send since we're in a blocking thread
                    if tx.blocking_send(event).is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
    });

    EventStream { receiver: rx }
}

/// Hybrid routing macros module.
///
/// This module provides the `#[hybrid::route]` macro for annotating
/// inference functions with hybrid routing capabilities.
pub mod hybrid {
    /// Route decorator macro for hybrid inference stages.
    ///
    /// Use this macro to annotate functions that should be routed
    /// by the Xybrid orchestrator between local and cloud execution.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use xybrid_sdk::hybrid;
    ///
    /// #[hybrid::route]
    /// fn process_audio(input: String) -> String {
    ///     // Function will be executed via orchestrator
    ///     todo!()
    /// }
    /// ```
    pub use xybrid_macros::route;
}

/// Pipeline configuration loaded from YAML (legacy format).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct LegacyPipelineConfig {
    /// Pipeline name/description
    #[serde(default)]
    name: Option<String>,
    /// List of stage names to execute in order
    stages: Vec<String>,
    /// Input envelope configuration
    input: LegacyInputConfig,
    /// Legacy device-metrics block. Still parsed so existing YAMLs load,
    /// but the values are ignored — capabilities are detected at runtime
    /// and live resource signals come from `ResourceMonitor`.
    #[serde(default)]
    #[allow(dead_code)]
    metrics: Option<serde_yaml::Value>,
    /// Model availability mapping (stage name -> available locally)
    availability: HashMap<String, bool>,
}

/// Input envelope configuration (legacy format).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct LegacyInputConfig {
    /// Envelope kind (e.g., "AudioRaw", "Text", etc.)
    kind: String,
}

/// Timing information for a single pipeline stage.
#[derive(Debug, Clone, Serialize)]
pub struct StageTiming {
    /// Stage name
    pub name: String,
    /// Stage latency in milliseconds
    pub latency_ms: u32,
    /// Routing target (local, cloud, or fallback)
    pub target: String,
}

/// Result of pipeline execution with timing information.
#[derive(Debug, Clone, Serialize)]
pub struct PipelineResult {
    /// Pipeline name (if specified in config)
    pub name: Option<String>,
    /// Stage timing information
    pub stages: Vec<StageTiming>,
    /// Total pipeline latency in milliseconds
    pub total_latency_ms: u32,
    /// Final output envelope kind
    pub final_output: String,
}

/// Legacy error type for pipeline YAML execution (kept for backward compatibility).
/// For the new model API, use `model::SdkError`.
#[derive(Debug, thiserror::Error)]
pub enum PipelineConfigError {
    #[error("Failed to read config file: {0}")]
    ConfigReadError(String),
    #[error("Failed to parse YAML config: {0}")]
    ConfigParseError(String),
    #[error("Pipeline execution failed: {0}")]
    ExecutionError(String),
}

/// Run a pipeline from a configuration file.
///
/// This function loads a YAML configuration file, creates an orchestrator,
/// and executes the pipeline. Returns timing information for all stages.
///
/// # Arguments
///
/// * `config_path` - Path to the YAML configuration file
///
/// # Returns
///
/// A `PipelineResult` containing stage timings and total latency, or an error.
///
/// # Example
///
/// ```no_run
/// use xybrid_sdk::run_pipeline;
///
/// match run_pipeline("examples/hiiipe.yaml") {
///     Ok(result) => {
///         println!("Pipeline completed in {}ms", result.total_latency_ms);
///         for stage in &result.stages {
///             println!("  {}: {}ms ({})", stage.name, stage.latency_ms, stage.target);
///         }
///     }
///     Err(e) => eprintln!("Pipeline failed: {}", e),
/// }
/// ```
pub fn run_pipeline(config_path: &str) -> Result<PipelineResult, PipelineConfigError> {
    // Load and parse configuration file
    let config_content = fs::read_to_string(config_path)
        .map_err(|e| PipelineConfigError::ConfigReadError(format!("{}: {}", config_path, e)))?;

    let config: LegacyPipelineConfig = serde_yaml::from_str(&config_content)
        .map_err(|e| PipelineConfigError::ConfigParseError(format!("{}: {}", config_path, e)))?;

    // Log pipeline start
    if let Some(name) = &config.name {
        log::info!(target: "xybrid_sdk", "Running pipeline: {}", name);
    } else {
        log::info!(target: "xybrid_sdk", "Running pipeline from: {}", config_path);
    }

    // Build stage descriptors from config
    let stages: Vec<StageDescriptor> = config
        .stages
        .iter()
        .map(|name| StageDescriptor::new(name.clone()))
        .collect();

    log::debug!(target: "xybrid_sdk", "Pipeline has {} stages", stages.len());

    // Create input envelope
    let kind = match config.input.kind.as_str() {
        "Audio" | "audio" => EnvelopeKind::Audio(vec![]),
        "Text" | "text" => EnvelopeKind::Text(String::new()),
        "Embedding" | "embedding" => EnvelopeKind::Embedding(vec![]),
        _ => EnvelopeKind::Text(config.input.kind.clone()),
    };
    let input = Envelope::new(kind);

    // Create device metrics
    let metrics = DeviceMetrics::default();

    // Ignore legacy availability hints because these configs have no resolved
    // bundle paths. Without a bundle path or preloaded adapter, local execution
    // is not runnable.
    if !config.availability.is_empty() {
        log::warn!(
            target: "xybrid_sdk",
            "Legacy pipeline availability hints are ignored; use PipelineRef::load() and load_models() for local execution"
        );
    }
    let availability_fn =
        move |_stage: &str| -> LocalAvailability { LocalAvailability::new(false) };

    // Create orchestrator
    let mut orchestrator = Orchestrator::new();
    let orchestrator_bridge = telemetry::subscribe_orchestrator_events(&orchestrator);

    // Execute the pipeline
    let start_time = std::time::Instant::now();
    let results: Vec<StageExecutionResult> = orchestrator
        .execute_pipeline(&stages, &input, &metrics, &availability_fn)
        .map_err(|e| {
            orchestrator_bridge.drain();
            PipelineConfigError::ExecutionError(format!("{}", e))
        })?;
    orchestrator_bridge.drain();
    let total_latency_ms = start_time.elapsed().as_millis() as u32;

    // Convert to SDK result format
    let stage_timings: Vec<StageTiming> = results
        .iter()
        .map(|result| StageTiming {
            name: result.stage.clone(),
            latency_ms: result.latency_ms,
            target: result.routing_decision.target.to_string(),
        })
        .collect();

    let final_output = results
        .last()
        .map(|r| r.output.kind_str().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    log::info!(target: "xybrid_sdk", "Pipeline completed in {}ms", total_latency_ms);

    Ok(PipelineResult {
        name: config.name.clone(),
        stages: stage_timings,
        total_latency_ms,
        final_output,
    })
}

/// Run a pipeline from a configuration file asynchronously.
///
/// This function loads a YAML configuration file, creates an orchestrator,
/// and executes the pipeline asynchronously. Returns timing information for all stages.
///
/// # Arguments
///
/// * `config_path` - Path to the YAML configuration file
///
/// # Returns
///
/// A future that resolves to a `PipelineResult` containing stage timings and total latency, or an error.
///
/// # Example
///
/// ```no_run
/// use xybrid_sdk::run_pipeline_async;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let result = run_pipeline_async("examples/hiiipe.yaml").await?;
/// println!("Pipeline completed in {}ms", result.total_latency_ms);
/// for stage in &result.stages {
///     println!("  {}: {}ms ({})", stage.name, stage.latency_ms, stage.target);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn run_pipeline_async(config_path: &str) -> Result<PipelineResult, PipelineConfigError> {
    // Load and parse configuration file
    let config_content = tokio::fs::read_to_string(config_path)
        .await
        .map_err(|e| PipelineConfigError::ConfigReadError(format!("{}: {}", config_path, e)))?;

    let config: LegacyPipelineConfig = serde_yaml::from_str(&config_content)
        .map_err(|e| PipelineConfigError::ConfigParseError(format!("{}: {}", config_path, e)))?;

    // Log pipeline start
    if let Some(name) = &config.name {
        log::info!(target: "xybrid_sdk", "Running pipeline (async): {}", name);
    } else {
        log::info!(target: "xybrid_sdk", "Running pipeline (async) from: {}", config_path);
    }

    // Build stage descriptors from config
    let stages: Vec<StageDescriptor> = config
        .stages
        .iter()
        .map(|name| StageDescriptor::new(name.clone()))
        .collect();

    log::debug!(target: "xybrid_sdk", "Pipeline has {} stages", stages.len());

    // Create input envelope
    let kind = match config.input.kind.as_str() {
        "Audio" | "audio" => EnvelopeKind::Audio(vec![]),
        "Text" | "text" => EnvelopeKind::Text(String::new()),
        "Embedding" | "embedding" => EnvelopeKind::Embedding(vec![]),
        _ => EnvelopeKind::Text(config.input.kind.clone()),
    };
    let input = Envelope::new(kind);

    // Create device metrics
    let metrics = DeviceMetrics::default();

    // Ignore legacy availability hints because these configs have no resolved
    // bundle paths. Without a bundle path or preloaded adapter, local execution
    // is not runnable.
    if !config.availability.is_empty() {
        log::warn!(
            target: "xybrid_sdk",
            "Legacy pipeline availability hints are ignored; use PipelineRef::load() and load_models() for local execution"
        );
    }
    let availability_fn =
        move |_stage: &str| -> LocalAvailability { LocalAvailability::new(false) };

    // Create orchestrator
    let mut orchestrator = Orchestrator::new();
    let orchestrator_bridge = telemetry::subscribe_orchestrator_events(&orchestrator);

    // Execute the pipeline asynchronously
    let start_time = std::time::Instant::now();
    let results: Vec<StageExecutionResult> = orchestrator
        .execute_pipeline_async(&stages, &input, &metrics, &availability_fn)
        .await
        .map_err(|e| {
            orchestrator_bridge.drain();
            PipelineConfigError::ExecutionError(format!("{}", e))
        })?;
    orchestrator_bridge.drain();
    let total_latency_ms = start_time.elapsed().as_millis() as u32;

    // Convert to SDK result format
    let stage_timings: Vec<StageTiming> = results
        .iter()
        .map(|result| StageTiming {
            name: result.stage.clone(),
            latency_ms: result.latency_ms,
            target: result.routing_decision.target.to_string(),
        })
        .collect();

    let final_output = results
        .last()
        .map(|r| r.output.kind_str().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    log::info!(target: "xybrid_sdk", "Pipeline completed in {}ms", total_latency_ms);

    Ok(PipelineResult {
        name: config.name.clone(),
        stages: stage_timings,
        total_latency_ms,
        final_output,
    })
}

#[cfg(test)]
mod sdk_config_tests {
    use super::{SdkConfig, DEFAULT_BINDING};

    #[test]
    fn default_binding_is_rust() {
        assert_eq!(DEFAULT_BINDING, "rust");
    }

    #[test]
    fn default_config_resolves_to_default_binding() {
        let cfg = SdkConfig::default();
        assert!(cfg.binding.is_none());
        assert_eq!(cfg.binding(), "rust");
    }

    #[test]
    fn with_binding_overrides_default() {
        let cfg = SdkConfig::default().with_binding("flutter");
        assert_eq!(cfg.binding, Some("flutter"));
        assert_eq!(cfg.binding(), "flutter");
    }

    #[test]
    fn with_binding_preserves_other_fields() {
        let cfg = SdkConfig {
            cache_dir: Some(std::path::PathBuf::from("/tmp/xybrid-cache")),
            ..SdkConfig::default()
        }
        .with_binding("kotlin");
        assert_eq!(cfg.binding(), "kotlin");
        assert_eq!(
            cfg.cache_dir.as_deref(),
            Some(std::path::Path::new("/tmp/xybrid-cache"))
        );
    }
}

#[cfg(test)]
mod xybrid_init_tests {
    use super::{init, XybridInit};
    use xybrid_core::device::ResourceTelemetryMode;

    #[test]
    fn init_returns_default_anonymous_builder() {
        let builder = init();
        let default = XybridInit::default();
        // Default builder carries no configuration — the anonymous path.
        assert_eq!(format!("{:?}", builder), format!("{:?}", default));
    }

    #[test]
    fn api_key_setter_stores_value() {
        let builder = init().api_key("xy_test_123");
        let dbg = format!("{:?}", builder);
        assert!(dbg.contains("xy_test_123"), "debug = {}", dbg);
    }

    #[test]
    fn cache_dir_setter_stores_path() {
        let builder = init().cache_dir("/tmp/xybrid-test-cache");
        let dbg = format!("{:?}", builder);
        assert!(
            dbg.contains("xybrid-test-cache"),
            "cache_dir not stored, debug = {}",
            dbg
        );
    }

    #[test]
    fn ingest_url_setter_stores_value() {
        let builder = init().ingest_url("http://192.168.1.78:8081");
        let dbg = format!("{:?}", builder);
        assert!(dbg.contains("192.168.1.78"), "debug = {}", dbg);
    }

    #[test]
    fn gateway_url_setter_stores_value() {
        let builder = init().gateway_url("https://gateway.example/v1");
        let dbg = format!("{:?}", builder);
        assert!(dbg.contains("gateway.example"), "debug = {}", dbg);
    }

    #[test]
    fn resource_telemetry_setter_stores_mode() {
        let builder = init().resource_telemetry(ResourceTelemetryMode::Boundary);
        let dbg = format!("{:?}", builder);
        assert!(dbg.contains("Boundary"), "debug = {}", dbg);
    }

    #[test]
    fn builder_is_chainable() {
        let _builder = init()
            .api_key("xy_test")
            .cache_dir("/tmp/x")
            .gateway_url("https://gateway")
            .ingest_url("https://ingest")
            .resource_telemetry(ResourceTelemetryMode::Off)
            .binding("rust");
    }
}