bzzz-core 0.1.0

Bzzz core library - Declarative orchestration engine for AI Agents
Documentation
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
//! Distributed Tracing Module
//!
//! Provides W3C Trace Context compatible distributed tracing support.
//!
//! # Features
//!
//! - W3C Trace Context format (traceparent/tracestate)
//! - Span creation and lifecycle management
//! - Parent-child span relationships
//! - Span attributes and events
//! - Integration with structured logging (LogEntry)
//!
//! # Example
//!
//! ```
//! use bzzz_core::{Tracer, SpanBuilder, SpanKind, SpanStatus, TraceContext};
//!
//! // Create a root span
//! let tracer = Tracer::new();
//! let mut span = tracer.span_builder("run-execution")
//!     .with_kind(SpanKind::Internal)
//!     .with_attribute("swarm_name", "my-swarm")
//!     .start(&tracer);
//!
//! // Create a child span
//! let mut child_span = tracer.span_builder("worker-execution")
//!     .with_parent(span.context())
//!     .start(&tracer);
//!
//! // End spans
//! child_span.end();
//! span.end();
//!
//! // Export trace context for propagation
//! let ctx = span.context();
//! println!("traceparent: {}", ctx.traceparent());
//! ```
//!
//! # W3C Trace Context Format
//!
//! The traceparent header format is:
//! `traceparent: {version}-{trace-id}-{parent-id}-{trace-flags}`
//!
//! - version: 00 (fixed)
//! - trace-id: 32 lowercase hex chars (16 bytes)
//! - parent-id: 16 lowercase hex chars (8 bytes)
//! - trace-flags: 2 lowercase hex chars (1 byte, e.g., 01 for sampled)

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Serialize, Serializer};

use crate::RunId;

// ============================================================================
// ID Types
// ============================================================================

/// Trace identifier (32 lowercase hex chars, 16 bytes)
///
/// Follows W3C Trace Context specification.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraceId([u8; 16]);

impl TraceId {
    /// Generate a new random TraceId
    pub fn new() -> Self {
        // Use random bytes for trace ID
        let mut bytes = [0u8; 16];
        for byte in &mut bytes {
            *byte = (rand_byte() % 256) as u8;
        }
        // Ensure at least one non-zero byte (W3C spec)
        if bytes.iter().all(|b| *b == 0) {
            bytes[0] = 1;
        }
        TraceId(bytes)
    }

    /// Create from hex string (32 chars)
    pub fn from_hex(hex: &str) -> Option<Self> {
        if hex.len() != 32 {
            return None;
        }
        let mut bytes = [0u8; 16];
        for i in 0..16 {
            let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;
            bytes[i] = byte;
        }
        // All-zeros is invalid per W3C spec
        if bytes.iter().all(|b| *b == 0) {
            return None;
        }
        Some(TraceId(bytes))
    }

    /// Convert to hex string
    pub fn to_hex(&self) -> String {
        self.0.iter().map(|b| format!("{:02x}", b)).collect()
    }

    /// Get the raw bytes
    pub fn as_bytes(&self) -> &[u8; 16] {
        &self.0
    }
}

impl Default for TraceId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for TraceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Serialize for TraceId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_hex())
    }
}

/// Span identifier (16 lowercase hex chars, 8 bytes)
///
/// Follows W3C Trace Context specification.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SpanId([u8; 8]);

impl SpanId {
    /// Generate a new random SpanId
    pub fn new() -> Self {
        let mut bytes = [0u8; 8];
        for byte in &mut bytes {
            *byte = (rand_byte() % 256) as u8;
        }
        // Ensure at least one non-zero byte (W3C spec)
        if bytes.iter().all(|b| *b == 0) {
            bytes[0] = 1;
        }
        SpanId(bytes)
    }

    /// Create from hex string (16 chars)
    pub fn from_hex(hex: &str) -> Option<Self> {
        if hex.len() != 16 {
            return None;
        }
        let mut bytes = [0u8; 8];
        for i in 0..8 {
            let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;
            bytes[i] = byte;
        }
        // All-zeros is invalid per W3C spec
        if bytes.iter().all(|b| *b == 0) {
            return None;
        }
        Some(SpanId(bytes))
    }

    /// Convert to hex string
    pub fn to_hex(&self) -> String {
        self.0.iter().map(|b| format!("{:02x}", b)).collect()
    }

    /// Get the raw bytes
    pub fn as_bytes(&self) -> &[u8; 8] {
        &self.0
    }
}

impl Default for SpanId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for SpanId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Serialize for SpanId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_hex())
    }
}

/// Simple random byte generator (no external dependencies)
fn rand_byte() -> u32 {
    // Use system time as entropy source
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    // Mix with a counter for more entropy
    static COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    let count = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    // Combine time and counter
    ((now.as_nanos() as u32) ^ count ^ 0xDEADBEEF) & 0xFF
}

// ============================================================================
// Span Types
// ============================================================================

/// Kind of span
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SpanKind {
    /// Internal operation within a service
    Internal,
    /// Client making a request to external service
    Client,
    /// Server handling a request
    Server,
    /// Producer sending to a message broker
    Producer,
    /// Consumer receiving from a message broker
    Consumer,
}

impl fmt::Display for SpanKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpanKind::Internal => write!(f, "INTERNAL"),
            SpanKind::Client => write!(f, "CLIENT"),
            SpanKind::Server => write!(f, "SERVER"),
            SpanKind::Producer => write!(f, "PRODUCER"),
            SpanKind::Consumer => write!(f, "CONSUMER"),
        }
    }
}

/// Status of a span
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SpanStatus {
    /// Operation completed successfully
    Ok,
    /// Operation failed with error
    Error,
    /// Operation was cancelled
    Cancelled,
}

impl fmt::Display for SpanStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpanStatus::Ok => write!(f, "OK"),
            SpanStatus::Error => write!(f, "ERROR"),
            SpanStatus::Cancelled => write!(f, "CANCELLED"),
        }
    }
}

/// A timed event within a span
#[derive(Debug, Clone, Serialize)]
pub struct SpanEvent {
    /// Event name
    pub name: String,
    /// Timestamp (Unix epoch milliseconds)
    #[serde(rename = "timestampMs")]
    pub timestamp_ms: u64,
    /// Event attributes
    #[serde(flatten)]
    pub attributes: HashMap<String, serde_json::Value>,
}

impl SpanEvent {
    /// Create a new span event
    pub fn new(name: impl Into<String>) -> Self {
        SpanEvent {
            name: name.into(),
            timestamp_ms: current_time_ms(),
            attributes: HashMap::new(),
        }
    }

    /// Add an attribute
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
        if let Ok(json_value) = serde_json::to_value(value) {
            self.attributes.insert(key.into(), json_value);
        }
        self
    }
}

/// Span attributes (key-value pairs)
#[derive(Debug, Clone, Default, Serialize)]
pub struct SpanAttributes(HashMap<String, serde_json::Value>);

impl SpanAttributes {
    /// Create empty attributes
    pub fn new() -> Self {
        SpanAttributes(HashMap::new())
    }

    /// Add an attribute
    pub fn insert(&mut self, key: impl Into<String>, value: impl Serialize) {
        if let Ok(json_value) = serde_json::to_value(value) {
            self.0.insert(key.into(), json_value);
        }
    }

    /// Get an attribute
    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.0.get(key)
    }

    /// Check if attribute exists
    pub fn contains(&self, key: &str) -> bool {
        self.0.contains_key(key)
    }

    /// Get all attributes as map
    pub fn as_map(&self) -> &HashMap<String, serde_json::Value> {
        &self.0
    }

    /// Number of attributes
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// A unit of work within a trace
#[derive(Debug, Clone, Serialize)]
pub struct Span {
    /// Trace ID
    #[serde(rename = "traceId")]
    pub trace_id: TraceId,
    /// Span ID
    #[serde(rename = "spanId")]
    pub span_id: SpanId,
    /// Parent span ID (None for root span)
    #[serde(rename = "parentSpanId", skip_serializing_if = "Option::is_none")]
    pub parent_span_id: Option<SpanId>,
    /// Span name
    pub name: String,
    /// Span kind
    pub kind: SpanKind,
    /// Start timestamp (Unix epoch milliseconds)
    #[serde(rename = "startTimeMs")]
    pub start_time_ms: u64,
    /// End timestamp (None if span is still active)
    #[serde(rename = "endTimeMs", skip_serializing_if = "Option::is_none")]
    pub end_time_ms: Option<u64>,
    /// Span status
    pub status: SpanStatus,
    /// Span attributes
    #[serde(flatten)]
    pub attributes: SpanAttributes,
    /// Span events
    #[serde(rename = "events", skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<SpanEvent>,
    /// Associated Run ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_id: Option<String>,
}

impl Span {
    /// Get the trace context for this span
    pub fn context(&self) -> TraceContext {
        TraceContext {
            trace_id: self.trace_id.clone(),
            parent_id: self.span_id.clone(),
            trace_flags: if self.status == SpanStatus::Ok {
                TraceFlags::SAMPLED
            } else {
                TraceFlags::default()
            },
        }
    }

    /// End the span
    pub fn end(&mut self) {
        self.end_time_ms = Some(current_time_ms());
    }

    /// End with status
    pub fn end_with_status(&mut self, status: SpanStatus) {
        self.status = status;
        self.end();
    }

    /// Add an attribute
    pub fn set_attribute(&mut self, key: impl Into<String>, value: impl Serialize) {
        self.attributes.insert(key, value);
    }

    /// Add an event
    pub fn add_event(&mut self, name: impl Into<String>) {
        self.events.push(SpanEvent::new(name));
    }

    /// Add an event with attributes
    pub fn add_event_with_attrs(&mut self, name: impl Into<String>, attrs: SpanAttributes) {
        let mut event = SpanEvent::new(name);
        for (key, value) in attrs.as_map().iter() {
            event.attributes.insert(key.clone(), value.clone());
        }
        self.events.push(event);
    }

    /// Set status
    pub fn set_status(&mut self, status: SpanStatus) {
        self.status = status;
    }

    /// Set Run ID
    pub fn set_run_id(&mut self, run_id: &RunId) {
        self.run_id = Some(run_id.as_str().to_string());
    }

    /// Get duration in milliseconds
    pub fn duration_ms(&self) -> Option<u64> {
        self.end_time_ms.map(|end| end - self.start_time_ms)
    }

    /// Convert to JSON
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| {
            format!(
                r#"{{"traceId":"{}","spanId":"{}","name":"{}"}}"#,
                self.trace_id, self.span_id, self.name
            )
        })
    }

    /// Check if span has ended
    pub fn is_ended(&self) -> bool {
        self.end_time_ms.is_some()
    }
}

// ============================================================================
// Trace Context
// ============================================================================

/// Trace flags (1 byte, following W3C spec)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TraceFlags(u8);

impl TraceFlags {
    /// Trace is sampled
    pub const SAMPLED: TraceFlags = TraceFlags(0x01);

    /// Create new trace flags
    pub fn new(value: u8) -> Self {
        TraceFlags(value)
    }

    /// Check if sampled
    pub fn is_sampled(&self) -> bool {
        (self.0 & 0x01) != 0
    }

    /// Get the raw value
    pub fn value(&self) -> u8 {
        self.0
    }

    /// Convert to hex string (2 chars)
    pub fn to_hex(&self) -> String {
        format!("{:02x}", self.0)
    }
}

impl fmt::Display for TraceFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Serialize for TraceFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_hex())
    }
}

/// Trace context for propagation (W3C Trace Context)
///
/// Contains traceparent format: `{version}-{trace-id}-{parent-id}-{trace-flags}`
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TraceContext {
    /// Trace ID (32 hex chars)
    pub trace_id: TraceId,
    /// Parent/Span ID (16 hex chars)
    pub parent_id: SpanId,
    /// Trace flags (2 hex chars)
    pub trace_flags: TraceFlags,
}

impl TraceContext {
    /// Create a new trace context (root span)
    pub fn new() -> Self {
        TraceContext {
            trace_id: TraceId::new(),
            parent_id: SpanId::new(),
            trace_flags: TraceFlags::SAMPLED,
        }
    }

    /// Create from traceparent header
    ///
    /// Format: `{version}-{trace-id}-{parent-id}-{trace-flags}`
    /// Example: `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`
    pub fn from_traceparent(traceparent: &str) -> Option<Self> {
        let parts: Vec<&str> = traceparent.split('-').collect();
        if parts.len() != 4 {
            return None;
        }

        // Version must be "00"
        if parts[0] != "00" {
            return None;
        }

        let trace_id = TraceId::from_hex(parts[1])?;
        let parent_id = SpanId::from_hex(parts[2])?;

        // Parse flags (2 hex chars)
        if parts[3].len() != 2 {
            return None;
        }
        let flags = u8::from_str_radix(parts[3], 16).ok()?;
        let trace_flags = TraceFlags::new(flags);

        Some(TraceContext {
            trace_id,
            parent_id,
            trace_flags,
        })
    }

    /// Generate traceparent header value
    ///
    /// Format: `00-{trace_id}-{parent_id}-{flags}`
    pub fn traceparent(&self) -> String {
        format!(
            "00-{}-{}-{}",
            self.trace_id.to_hex(),
            self.parent_id.to_hex(),
            self.trace_flags.to_hex()
        )
    }

    /// Create a child context (new span ID, same trace ID)
    pub fn child(&self) -> TraceContext {
        TraceContext {
            trace_id: self.trace_id.clone(),
            parent_id: SpanId::new(),
            trace_flags: self.trace_flags,
        }
    }

    /// Check if this trace is sampled
    pub fn is_sampled(&self) -> bool {
        self.trace_flags.is_sampled()
    }

    /// Convert to JSON
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| {
            format!(
                r#"{{"trace_id":"{}","parent_id":"{}","trace_flags":"{}"}}"#,
                self.trace_id, self.parent_id, self.trace_flags
            )
        })
    }
}

impl Default for TraceContext {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Span Builder
// ============================================================================

/// Builder for creating spans
pub struct SpanBuilder {
    /// Span name
    name: String,
    /// Span kind
    kind: SpanKind,
    /// Parent trace context (None for root span)
    parent_context: Option<TraceContext>,
    /// Initial attributes
    attributes: SpanAttributes,
    /// Associated Run ID
    run_id: Option<RunId>,
}

impl SpanBuilder {
    /// Create a new span builder
    pub fn new(name: impl Into<String>) -> Self {
        SpanBuilder {
            name: name.into(),
            kind: SpanKind::Internal,
            parent_context: None,
            attributes: SpanAttributes::new(),
            run_id: None,
        }
    }

    /// Set span kind
    pub fn with_kind(mut self, kind: SpanKind) -> Self {
        self.kind = kind;
        self
    }

    /// Set parent context
    pub fn with_parent(mut self, parent: TraceContext) -> Self {
        self.parent_context = Some(parent);
        self
    }

    /// Add an attribute
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
        self.attributes.insert(key, value);
        self
    }

    /// Add multiple attributes
    pub fn with_attributes(mut self, attrs: SpanAttributes) -> Self {
        for (key, value) in attrs.as_map().iter() {
            self.attributes.0.insert(key.clone(), value.clone());
        }
        self
    }

    /// Set Run ID
    pub fn with_run_id(mut self, run_id: RunId) -> Self {
        self.run_id = Some(run_id);
        self
    }

    /// Start the span
    pub fn start(self, tracer: &Tracer) -> Span {
        tracer.start_span(self)
    }
}

// ============================================================================
// Tracer
// ============================================================================

/// Tracer for creating spans
#[derive(Debug, Clone)]
pub struct Tracer {
    /// Service name for all spans
    service_name: String,
}

impl Tracer {
    /// Create a new tracer
    pub fn new() -> Self {
        Tracer {
            service_name: "bzzz".to_string(),
        }
    }

    /// Create tracer with custom service name
    pub fn with_service_name(name: impl Into<String>) -> Self {
        Tracer {
            service_name: name.into(),
        }
    }

    /// Create a span builder
    pub fn span_builder(&self, name: impl Into<String>) -> SpanBuilder {
        SpanBuilder::new(name)
    }

    /// Start a span from a builder
    pub fn start_span(&self, builder: SpanBuilder) -> Span {
        let (trace_id, span_id, parent_span_id) = match builder.parent_context {
            Some(ctx) => (ctx.trace_id.clone(), SpanId::new(), Some(ctx.parent_id)),
            None => (TraceId::new(), SpanId::new(), None),
        };

        Span {
            trace_id,
            span_id,
            parent_span_id,
            name: builder.name,
            kind: builder.kind,
            start_time_ms: current_time_ms(),
            end_time_ms: None,
            status: SpanStatus::Ok,
            attributes: builder.attributes,
            events: Vec::new(),
            run_id: builder.run_id.map(|r| r.as_str().to_string()),
        }
    }

    /// Create a root span
    pub fn root_span(&self, name: impl Into<String>) -> Span {
        self.span_builder(name).start(self)
    }

    /// Create a child span
    pub fn child_span(&self, name: impl Into<String>, parent: &TraceContext) -> Span {
        self.span_builder(name)
            .with_parent(parent.clone())
            .start(self)
    }

    /// Get service name
    pub fn service_name(&self) -> &str {
        &self.service_name
    }
}

impl Default for Tracer {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Get current time in milliseconds since Unix epoch
fn current_time_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Global tracer instance
static GLOBAL_TRACER: std::sync::OnceLock<Tracer> = std::sync::OnceLock::new();

/// Get the global tracer
pub fn global_tracer() -> &'static Tracer {
    GLOBAL_TRACER.get_or_init(Tracer::new)
}

/// Initialize the global tracer
pub fn init_global_tracer(service_name: impl Into<String>) {
    let _ = GLOBAL_TRACER.get_or_init(|| Tracer::with_service_name(service_name));
}

// ============================================================================
// Integration with LogEntry
// ============================================================================

use crate::runtime::logging::LogEntry;

/// Extension trait for LogEntry to add trace context
pub trait LogEntryTraceExt {
    /// Add trace context to log entry
    fn with_trace_context(self, ctx: &TraceContext) -> Self;
}

impl LogEntryTraceExt for LogEntry {
    fn with_trace_context(mut self, ctx: &TraceContext) -> Self {
        self.fields.insert(
            "trace_id".into(),
            serde_json::Value::String(ctx.trace_id.to_hex()),
        );
        self.fields.insert(
            "span_id".into(),
            serde_json::Value::String(ctx.parent_id.to_hex()),
        );
        self.fields.insert(
            "traceparent".into(),
            serde_json::Value::String(ctx.traceparent()),
        );
        self
    }
}

// ============================================================================
// Span Export
// ============================================================================

/// Span exporter for collecting completed spans
pub trait SpanExporter: std::fmt::Debug {
    /// Export a completed span
    fn export(&self, span: &Span);
}

/// Simple in-memory span exporter for testing
#[derive(Debug, Clone, Default)]
pub struct InMemoryExporter {
    spans: Arc<std::sync::Mutex<Vec<Span>>>,
}

impl InMemoryExporter {
    /// Create a new in-memory exporter
    pub fn new() -> Self {
        InMemoryExporter {
            spans: Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }

    /// Get all exported spans
    pub fn get_spans(&self) -> Vec<Span> {
        self.spans.lock().unwrap().clone()
    }

    /// Clear all spans
    pub fn clear(&self) {
        self.spans.lock().unwrap().clear();
    }

    /// Number of exported spans
    pub fn len(&self) -> usize {
        self.spans.lock().unwrap().len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.spans.lock().unwrap().is_empty()
    }
}

impl SpanExporter for InMemoryExporter {
    fn export(&self, span: &Span) {
        self.spans.lock().unwrap().push(span.clone());
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trace_id_generation() {
        let id1 = TraceId::new();
        let id2 = TraceId::new();
        assert_ne!(id1, id2);
        assert_eq!(id1.to_hex().len(), 32);
    }

    #[test]
    fn test_trace_id_from_hex() {
        let hex = "4bf92f3577b34da6a3ce929d0e0e4736";
        let id = TraceId::from_hex(hex).unwrap();
        assert_eq!(id.to_hex(), hex);

        // Invalid: all zeros
        assert!(TraceId::from_hex("00000000000000000000000000000000").is_none());

        // Invalid: wrong length
        assert!(TraceId::from_hex("abcd").is_none());
    }

    #[test]
    fn test_span_id_generation() {
        let id1 = SpanId::new();
        let id2 = SpanId::new();
        assert_ne!(id1, id2);
        assert_eq!(id1.to_hex().len(), 16);
    }

    #[test]
    fn test_span_id_from_hex() {
        let hex = "00f067aa0ba902b7";
        let id = SpanId::from_hex(hex).unwrap();
        assert_eq!(id.to_hex(), hex);

        // Invalid: all zeros
        assert!(SpanId::from_hex("0000000000000000").is_none());

        // Invalid: wrong length
        assert!(SpanId::from_hex("abcd").is_none());
    }

    #[test]
    fn test_trace_context_creation() {
        let ctx = TraceContext::new();
        assert!(ctx.is_sampled());
        assert!(ctx.traceparent().starts_with("00-"));
    }

    #[test]
    fn test_trace_context_from_traceparent() {
        let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
        let ctx = TraceContext::from_traceparent(traceparent).unwrap();
        assert_eq!(ctx.traceparent(), traceparent);
        assert!(ctx.is_sampled());
    }

    #[test]
    fn test_trace_context_invalid_traceparent() {
        // Wrong version
        assert!(TraceContext::from_traceparent("01-abcd-efgh-01").is_none());

        // Wrong format
        assert!(TraceContext::from_traceparent("invalid").is_none());

        // Missing parts
        assert!(TraceContext::from_traceparent("00-abcd").is_none());
    }

    #[test]
    fn test_trace_context_child() {
        let parent = TraceContext::new();
        let child = parent.child();
        // Child should share the same trace_id
        assert_eq!(parent.trace_id, child.trace_id);
        // Child should inherit trace_flags
        assert_eq!(parent.trace_flags, child.trace_flags);
        // parent_id values are independently random, may or may not differ
    }

    #[test]
    fn test_span_creation() {
        let tracer = Tracer::new();
        let span = tracer.root_span("test-span");

        assert_eq!(span.name, "test-span");
        assert_eq!(span.kind, SpanKind::Internal);
        assert!(span.parent_span_id.is_none());
        assert!(!span.is_ended());
    }

    #[test]
    fn test_span_with_parent() {
        let tracer = Tracer::new();
        let parent_span = tracer.root_span("parent");
        let child_span = tracer.child_span("child", &parent_span.context());

        assert!(child_span.parent_span_id.is_some());
        assert_eq!(child_span.trace_id, parent_span.trace_id);
        assert_eq!(child_span.parent_span_id.unwrap(), parent_span.span_id);
    }

    #[test]
    fn test_span_lifecycle() {
        let tracer = Tracer::new();
        let mut span = tracer.root_span("test");

        assert!(!span.is_ended());

        span.set_attribute("key", "value");
        span.add_event("something happened");

        span.end();

        assert!(span.is_ended());
        assert!(span.duration_ms().is_some());
        assert!(span.attributes.contains("key"));
        assert_eq!(span.events.len(), 1);
    }

    #[test]
    fn test_span_status() {
        let tracer = Tracer::new();
        let mut span = tracer.root_span("test");

        assert_eq!(span.status, SpanStatus::Ok);

        span.end_with_status(SpanStatus::Error);

        assert_eq!(span.status, SpanStatus::Error);
        assert!(span.is_ended());
    }

    #[test]
    fn test_span_builder() {
        let tracer = Tracer::new();
        let span = tracer
            .span_builder("test")
            .with_kind(SpanKind::Server)
            .with_attribute("http.method", "GET")
            .with_attribute("http.url", "/api/run")
            .start(&tracer);

        assert_eq!(span.kind, SpanKind::Server);
        assert!(span.attributes.contains("http.method"));
        assert!(span.attributes.contains("http.url"));
    }

    #[test]
    fn test_span_json() {
        let tracer = Tracer::new();
        let mut span = tracer.root_span("test");
        span.end();

        let json = span.to_json();
        assert!(json.contains("\"traceId\""));
        assert!(json.contains("\"spanId\""));
        assert!(json.contains("\"name\":\"test\""));
    }

    #[test]
    fn test_span_attributes() {
        let mut attrs = SpanAttributes::new();
        attrs.insert("string_key", "value");
        attrs.insert("number_key", 42);
        attrs.insert("bool_key", true);

        assert_eq!(attrs.len(), 3);
        assert!(attrs.contains("string_key"));
        assert_eq!(attrs.get("number_key").unwrap().as_u64(), Some(42));
    }

    #[test]
    fn test_span_event() {
        let event = SpanEvent::new("error")
            .with_attribute("error.type", "timeout")
            .with_attribute("error.message", "Connection timed out");

        assert_eq!(event.name, "error");
        assert!(event.attributes.contains_key("error.type"));
    }

    #[test]
    fn test_log_entry_with_trace() {
        use crate::runtime::logging::{LogEntry, LogLevel};

        let ctx = TraceContext::new();
        let entry = LogEntry::new(LogLevel::Info, "test").with_trace_context(&ctx);

        assert!(entry.fields.contains_key("trace_id"));
        assert!(entry.fields.contains_key("span_id"));
        assert!(entry.fields.contains_key("traceparent"));
    }

    #[test]
    fn test_in_memory_exporter() {
        let exporter = InMemoryExporter::new();
        let tracer = Tracer::new();
        let mut span = tracer.root_span("test");
        span.end();

        exporter.export(&span);

        assert_eq!(exporter.len(), 1);
        assert_eq!(exporter.get_spans()[0].name, "test");

        exporter.clear();
        assert!(exporter.is_empty());
    }

    #[test]
    fn test_global_tracer() {
        let tracer = global_tracer();
        let span = tracer.root_span("test");
        assert_eq!(span.name, "test");
    }

    #[test]
    fn test_span_with_run_id() {
        let tracer = Tracer::new();
        let run_id = RunId::new();
        let span = tracer
            .span_builder("test")
            .with_run_id(run_id.clone())
            .start(&tracer);

        assert!(span.run_id.is_some());
        assert_eq!(span.run_id.unwrap(), run_id.as_str());
    }

    #[test]
    fn test_trace_flags() {
        let flags = TraceFlags::SAMPLED;
        assert!(flags.is_sampled());
        assert_eq!(flags.to_hex(), "01");

        let unsampled = TraceFlags::default();
        assert!(!unsampled.is_sampled());
        assert_eq!(unsampled.to_hex(), "00");
    }

    #[test]
    fn test_tracer_service_name() {
        let tracer = Tracer::with_service_name("my-service");
        assert_eq!(tracer.service_name(), "my-service");
    }
}