fyi-core 0.1.0

Core types and traits for fyi
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;

/// Event types for Claude Code hooks and API requests.
///
/// Known event types are represented as enum variants for type safety.
/// Unknown event types (from future Claude Code versions) are captured
/// as `Custom(String)` to ensure forward compatibility.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EventType {
    /// Session begins
    SessionStart,
    /// Session ends
    SessionEnd,
    /// Before tool execution
    PreToolUse,
    /// After tool execution
    PostToolUse,
    /// User permission requested
    PermissionRequest,
    /// Before context compaction
    PreCompact,
    /// Execution stopped
    Stop,
    /// Subagent stopped
    SubagentStop,
    /// System notification
    Notification,
    /// User submitted prompt
    UserPromptSubmit,
    /// API request (from OpenTelemetry)
    ApiRequest,
    /// Unknown/future event type (forward compatibility)
    Custom(String),
}

impl EventType {
    /// Returns the canonical string representation of the event type.
    pub fn as_str(&self) -> &str {
        match self {
            EventType::SessionStart => "SessionStart",
            EventType::SessionEnd => "SessionEnd",
            EventType::PreToolUse => "PreToolUse",
            EventType::PostToolUse => "PostToolUse",
            EventType::PermissionRequest => "PermissionRequest",
            EventType::PreCompact => "PreCompact",
            EventType::Stop => "Stop",
            EventType::SubagentStop => "SubagentStop",
            EventType::Notification => "Notification",
            EventType::UserPromptSubmit => "UserPromptSubmit",
            EventType::ApiRequest => "ApiRequest",
            EventType::Custom(s) => s.as_str(),
        }
    }

    /// Returns true if this is a known (non-custom) event type.
    pub fn is_known(&self) -> bool {
        !matches!(self, EventType::Custom(_))
    }
}

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

impl FromStr for EventType {
    type Err = std::convert::Infallible;

    /// Parse an event type string (case-insensitive for known types).
    /// Unknown strings become `Custom(String)`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Trim whitespace and use case-insensitive matching for known types
        let trimmed = s.trim();
        Ok(match trimmed.to_ascii_lowercase().as_str() {
            "sessionstart" => EventType::SessionStart,
            "sessionend" => EventType::SessionEnd,
            "pretooluse" => EventType::PreToolUse,
            "posttooluse" => EventType::PostToolUse,
            "permissionrequest" => EventType::PermissionRequest,
            "precompact" => EventType::PreCompact,
            "stop" => EventType::Stop,
            "subagentstop" => EventType::SubagentStop,
            "notification" => EventType::Notification,
            "userpromptsubmit" => EventType::UserPromptSubmit,
            "apirequest" => EventType::ApiRequest,
            _ => EventType::Custom(trimmed.to_string()),
        })
    }
}

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

impl<'de> Deserialize<'de> for EventType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        // FromStr is infallible, so this always succeeds
        Ok(s.parse().unwrap())
    }
}

/// A hook event captured from Claude Code
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Database ID (None for new events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,

    /// Machine identifier for multi-machine sync
    pub machine_id: String,

    /// Event timestamp
    #[serde(with = "timestamp_millis")]
    pub timestamp: DateTime<Utc>,

    /// Event type (SessionStart, PreToolUse, etc.)
    pub event_type: EventType,

    /// Session ID from Claude Code
    pub session_id: String,

    /// Source framework (claude, cursor, gemini, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub framework: Option<String>,

    /// Tool use ID for correlating PreToolUse/PostToolUse
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_use_id: Option<String>,

    /// Child agent ID from PostToolUse for Task tool (links parent → child sessions)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spawned_agent_id: Option<String>,

    /// Tool name (Bash, Read, Write, Edit, Task, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,

    /// Subagent type for Task tool (Explore, Plan, claude-code-guide, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subagent_type: Option<String>,

    /// Permission mode (default, plan, acceptEdits, bypassPermissions)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,

    /// Path to the session transcript JSONL file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transcript_path: Option<String>,

    /// Parent process ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<i32>,

    /// Working directory
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,

    // API request fields (NULL for hook events, populated for ApiRequest events)
    /// Model used for API request (e.g., "claude-3-opus")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,

    /// Input tokens used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens_input: Option<i64>,

    /// Output tokens generated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens_output: Option<i64>,

    /// Tokens read from cache
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens_cache_read: Option<i64>,

    /// Tokens written to cache
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens_cache_creation: Option<i64>,

    /// Cost in USD
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cost_usd: Option<f64>,

    /// API call duration in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<i64>,

    /// JSON payload with all hook data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<String>,

    /// Extensible JSON metadata for future fields
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<String>,
}

impl Event {
    /// Create a new event with current timestamp
    pub fn new(machine_id: String, event_type: EventType, session_id: String) -> Self {
        Self {
            id: None,
            machine_id,
            timestamp: Utc::now(),
            event_type,
            session_id,
            framework: None,
            tool_use_id: None,
            spawned_agent_id: None,
            tool_name: None,
            subagent_type: None,
            permission_mode: None,
            transcript_path: None,
            pid: None,
            cwd: None,
            model: None,
            tokens_input: None,
            tokens_output: None,
            tokens_cache_read: None,
            tokens_cache_creation: None,
            cost_usd: None,
            duration_ms: None,
            payload: None,
            metadata: None,
        }
    }

    /// Check if this event is an API request (has token data)
    pub fn is_api_request(&self) -> bool {
        self.tokens_input.is_some() || self.tokens_output.is_some()
    }

    /// Total tokens (input + output) for API requests
    pub fn total_tokens(&self) -> i64 {
        self.tokens_input.unwrap_or(0) + self.tokens_output.unwrap_or(0)
    }

    pub fn with_framework(mut self, framework: Option<String>) -> Self {
        self.framework = framework;
        self
    }

    pub fn with_tool_use_id(mut self, tool_use_id: Option<String>) -> Self {
        self.tool_use_id = tool_use_id;
        self
    }

    pub fn with_spawned_agent_id(mut self, spawned_agent_id: Option<String>) -> Self {
        self.spawned_agent_id = spawned_agent_id;
        self
    }

    pub fn with_tool_name(mut self, tool_name: Option<String>) -> Self {
        self.tool_name = tool_name;
        self
    }

    pub fn with_subagent_type(mut self, subagent_type: Option<String>) -> Self {
        self.subagent_type = subagent_type;
        self
    }

    pub fn with_permission_mode(mut self, permission_mode: Option<String>) -> Self {
        self.permission_mode = permission_mode;
        self
    }

    pub fn with_transcript_path(mut self, transcript_path: Option<String>) -> Self {
        self.transcript_path = transcript_path;
        self
    }

    pub fn with_pid(mut self, pid: Option<i32>) -> Self {
        self.pid = pid;
        self
    }

    pub fn with_cwd(mut self, cwd: Option<String>) -> Self {
        self.cwd = cwd;
        self
    }

    pub fn with_model(mut self, model: Option<String>) -> Self {
        self.model = model;
        self
    }

    pub fn with_tokens_input(mut self, tokens_input: Option<i64>) -> Self {
        self.tokens_input = tokens_input;
        self
    }

    pub fn with_tokens_output(mut self, tokens_output: Option<i64>) -> Self {
        self.tokens_output = tokens_output;
        self
    }

    pub fn with_tokens_cache_read(mut self, tokens_cache_read: Option<i64>) -> Self {
        self.tokens_cache_read = tokens_cache_read;
        self
    }

    pub fn with_tokens_cache_creation(mut self, tokens_cache_creation: Option<i64>) -> Self {
        self.tokens_cache_creation = tokens_cache_creation;
        self
    }

    pub fn with_cost_usd(mut self, cost_usd: Option<f64>) -> Self {
        self.cost_usd = cost_usd;
        self
    }

    pub fn with_duration_ms(mut self, duration_ms: Option<i64>) -> Self {
        self.duration_ms = duration_ms;
        self
    }

    pub fn with_payload(mut self, payload: Option<String>) -> Self {
        self.payload = payload;
        self
    }

    pub fn with_metadata(mut self, metadata: Option<String>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set the timestamp (useful for testing)
    pub fn with_timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
        self.timestamp = timestamp;
        self
    }
}

/// Builder for creating Event instances with an ergonomic API.
///
/// Provides helper methods that group related fields together and accept
/// non-Option values directly, reducing verbosity compared to chained `with_*` calls.
///
/// # Method variants
///
/// - **Regular setters** (e.g., `framework()`, `model()`) accept values directly and always
///   set the field.
/// - **Optional setters** (e.g., `framework_opt()`, `model_opt()`) accept `Option<T>` and
///   only set the field if `Some` is passed; `None` preserves any previously set value.
/// - **Grouped helpers** (e.g., `tokens()`, `cache_tokens()`, `tool()`) set multiple related
///   fields at once for common patterns.
///
/// # Example
///
/// ```
/// use fyi_core::{EventBuilder, EventType};
///
/// // Building an API request event
/// let event = EventBuilder::new("machine-1", EventType::ApiRequest, "session-123")
///     .framework("claude")
///     .tokens(1000, 500)
///     .cache_tokens(200, 0)
///     .cost(0.05)
///     .model("claude-3-opus")
///     .build();
///
/// // Building a hook event
/// let event = EventBuilder::new("machine-1", EventType::PreToolUse, "session-123")
///     .framework("claude")
///     .tool("toolu_123", "Bash")
///     .payload(r#"{"command": "ls"}"#)
///     .build();
///
/// // Using _opt methods to conditionally set fields
/// let maybe_model: Option<String> = Some("claude-3-opus".to_string());
/// let event = EventBuilder::new("machine-1", EventType::ApiRequest, "session-123")
///     .model_opt(maybe_model)  // Sets model to "claude-3-opus"
///     .model_opt(None)         // Does nothing, preserves "claude-3-opus"
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct EventBuilder {
    event: Event,
}

impl EventBuilder {
    /// Create a new EventBuilder with required fields.
    ///
    /// The timestamp is set to the current time; use `timestamp()` to override.
    pub fn new(
        machine_id: impl Into<String>,
        event_type: EventType,
        session_id: impl Into<String>,
    ) -> Self {
        Self {
            event: Event::new(machine_id.into(), event_type, session_id.into()),
        }
    }

    /// Build the final Event.
    pub fn build(self) -> Event {
        self.event
    }

    // --- Grouped helper methods ---

    /// Set input and output tokens together.
    pub fn tokens(mut self, input: i64, output: i64) -> Self {
        self.event.tokens_input = Some(input);
        self.event.tokens_output = Some(output);
        self
    }

    /// Set cache read and cache creation tokens together.
    pub fn cache_tokens(mut self, read: i64, creation: i64) -> Self {
        self.event.tokens_cache_read = Some(read);
        self.event.tokens_cache_creation = Some(creation);
        self
    }

    /// Set tool_use_id and tool_name together (common for tool events).
    pub fn tool(mut self, tool_use_id: impl Into<String>, tool_name: impl Into<String>) -> Self {
        self.event.tool_use_id = Some(tool_use_id.into());
        self.event.tool_name = Some(tool_name.into());
        self
    }

    // --- Individual field setters (non-Option convenience) ---

    /// Set the framework.
    pub fn framework(mut self, framework: impl Into<String>) -> Self {
        self.event.framework = Some(framework.into());
        self
    }

    /// Set the model.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.event.model = Some(model.into());
        self
    }

    /// Set the cost in USD.
    pub fn cost(mut self, cost_usd: f64) -> Self {
        self.event.cost_usd = Some(cost_usd);
        self
    }

    /// Set the duration in milliseconds.
    pub fn duration_ms(mut self, duration: i64) -> Self {
        self.event.duration_ms = Some(duration);
        self
    }

    /// Set the timestamp.
    pub fn timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
        self.event.timestamp = timestamp;
        self
    }

    /// Set the payload JSON string.
    pub fn payload(mut self, payload: impl Into<String>) -> Self {
        self.event.payload = Some(payload.into());
        self
    }

    /// Set the metadata JSON string.
    pub fn metadata(mut self, metadata: impl Into<String>) -> Self {
        self.event.metadata = Some(metadata.into());
        self
    }

    /// Set the tool_use_id.
    pub fn tool_use_id(mut self, tool_use_id: impl Into<String>) -> Self {
        self.event.tool_use_id = Some(tool_use_id.into());
        self
    }

    /// Set the tool_name.
    pub fn tool_name(mut self, tool_name: impl Into<String>) -> Self {
        self.event.tool_name = Some(tool_name.into());
        self
    }

    /// Set the spawned_agent_id.
    pub fn spawned_agent_id(mut self, spawned_agent_id: impl Into<String>) -> Self {
        self.event.spawned_agent_id = Some(spawned_agent_id.into());
        self
    }

    /// Set the subagent_type.
    pub fn subagent_type(mut self, subagent_type: impl Into<String>) -> Self {
        self.event.subagent_type = Some(subagent_type.into());
        self
    }

    /// Set the permission_mode.
    pub fn permission_mode(mut self, permission_mode: impl Into<String>) -> Self {
        self.event.permission_mode = Some(permission_mode.into());
        self
    }

    /// Set the transcript_path.
    pub fn transcript_path(mut self, transcript_path: impl Into<String>) -> Self {
        self.event.transcript_path = Some(transcript_path.into());
        self
    }

    /// Set the cwd.
    pub fn cwd(mut self, cwd: impl Into<String>) -> Self {
        self.event.cwd = Some(cwd.into());
        self
    }

    /// Set the pid.
    pub fn pid(mut self, pid: i32) -> Self {
        self.event.pid = Some(pid);
        self
    }

    // --- Optional field setters (for passing through Option values) ---

    /// Set the framework if Some.
    pub fn framework_opt(mut self, framework: Option<String>) -> Self {
        if let Some(f) = framework {
            self.event.framework = Some(f);
        }
        self
    }

    /// Set the timestamp if Some.
    pub fn timestamp_opt(mut self, timestamp: Option<DateTime<Utc>>) -> Self {
        if let Some(ts) = timestamp {
            self.event.timestamp = ts;
        }
        self
    }

    /// Set the tool_use_id if Some.
    pub fn tool_use_id_opt(mut self, tool_use_id: Option<String>) -> Self {
        if let Some(id) = tool_use_id {
            self.event.tool_use_id = Some(id);
        }
        self
    }

    /// Set the tool_name if Some.
    pub fn tool_name_opt(mut self, tool_name: Option<String>) -> Self {
        if let Some(name) = tool_name {
            self.event.tool_name = Some(name);
        }
        self
    }

    /// Set the spawned_agent_id if Some.
    pub fn spawned_agent_id_opt(mut self, spawned_agent_id: Option<String>) -> Self {
        if let Some(id) = spawned_agent_id {
            self.event.spawned_agent_id = Some(id);
        }
        self
    }

    /// Set the subagent_type if Some.
    pub fn subagent_type_opt(mut self, subagent_type: Option<String>) -> Self {
        if let Some(t) = subagent_type {
            self.event.subagent_type = Some(t);
        }
        self
    }

    /// Set the permission_mode if Some.
    pub fn permission_mode_opt(mut self, permission_mode: Option<String>) -> Self {
        if let Some(m) = permission_mode {
            self.event.permission_mode = Some(m);
        }
        self
    }

    /// Set the transcript_path if Some.
    pub fn transcript_path_opt(mut self, transcript_path: Option<String>) -> Self {
        if let Some(p) = transcript_path {
            self.event.transcript_path = Some(p);
        }
        self
    }

    /// Set the cwd if Some.
    pub fn cwd_opt(mut self, cwd: Option<String>) -> Self {
        if let Some(c) = cwd {
            self.event.cwd = Some(c);
        }
        self
    }

    /// Set the pid if Some.
    pub fn pid_opt(mut self, pid: Option<i32>) -> Self {
        if let Some(p) = pid {
            self.event.pid = Some(p);
        }
        self
    }

    /// Set the model if Some.
    pub fn model_opt(mut self, model: Option<String>) -> Self {
        if let Some(m) = model {
            self.event.model = Some(m);
        }
        self
    }

    /// Set the tokens_cache_read if Some.
    pub fn tokens_cache_read_opt(mut self, tokens: Option<i64>) -> Self {
        if let Some(t) = tokens {
            self.event.tokens_cache_read = Some(t);
        }
        self
    }

    /// Set the tokens_cache_creation if Some.
    pub fn tokens_cache_creation_opt(mut self, tokens: Option<i64>) -> Self {
        if let Some(t) = tokens {
            self.event.tokens_cache_creation = Some(t);
        }
        self
    }

    /// Set the cost_usd if Some.
    pub fn cost_opt(mut self, cost: Option<f64>) -> Self {
        if let Some(c) = cost {
            self.event.cost_usd = Some(c);
        }
        self
    }

    /// Set the duration_ms if Some.
    pub fn duration_ms_opt(mut self, duration: Option<i64>) -> Self {
        if let Some(d) = duration {
            self.event.duration_ms = Some(d);
        }
        self
    }

    /// Set the metadata if Some.
    pub fn metadata_opt(mut self, metadata: Option<String>) -> Self {
        if let Some(m) = metadata {
            self.event.metadata = Some(m);
        }
        self
    }

    /// Set the payload if Some.
    pub fn payload_opt(mut self, payload: Option<String>) -> Self {
        if let Some(p) = payload {
            self.event.payload = Some(p);
        }
        self
    }
}

/// Aggregated statistics for API requests in a session
#[derive(Debug, Clone, Default)]
pub struct ApiStats {
    /// Session ID
    pub session_id: String,
    /// Total API requests
    pub request_count: i64,
    /// Total input tokens
    pub tokens_input: i64,
    /// Total output tokens
    pub tokens_output: i64,
    /// Total cache read tokens
    pub tokens_cache_read: i64,
    /// Total cache creation tokens
    pub tokens_cache_creation: i64,
    /// Total cost in USD
    pub cost_usd: f64,
    /// First request timestamp
    pub first_request_ts: Option<DateTime<Utc>>,
    /// Last request timestamp
    pub last_request_ts: Option<DateTime<Utc>>,
    /// Context size of most recent request (input + cache_read + cache_creation)
    pub context_latest: i64,
    /// Maximum context size across all requests
    pub context_peak: i64,
}

impl ApiStats {
    /// Total tokens across all categories
    pub fn total_tokens(&self) -> i64 {
        self.tokens_input + self.tokens_output + self.tokens_cache_read + self.tokens_cache_creation
    }

    /// Duration from first to last request
    pub fn duration(&self) -> Option<chrono::Duration> {
        match (self.first_request_ts, self.last_request_ts) {
            (Some(first), Some(last)) => Some(last - first),
            _ => None,
        }
    }
}

/// Serde module for serializing `DateTime<Utc>` as Unix milliseconds
pub mod timestamp_millis {
    use chrono::{DateTime, TimeZone, Utc};
    use serde::{self, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i64(date.timestamp_millis())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let millis = i64::deserialize(deserializer)?;
        Utc.timestamp_millis_opt(millis)
            .single()
            .ok_or_else(|| serde::de::Error::custom("invalid timestamp"))
    }
}

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

    /// Helper to parse EventType - infallible since unknown strings become Custom
    fn parse_event_type(s: &str) -> EventType {
        // EventType::from_str is infallible (Err type is Infallible)
        s.parse::<EventType>()
            .unwrap_or_else(|e: std::convert::Infallible| match e {})
    }

    #[test]
    fn test_event_type_parse_known_types() {
        assert_eq!(parse_event_type("SessionStart"), EventType::SessionStart);
        assert_eq!(parse_event_type("SessionEnd"), EventType::SessionEnd);
        assert_eq!(parse_event_type("PreToolUse"), EventType::PreToolUse);
        assert_eq!(parse_event_type("PostToolUse"), EventType::PostToolUse);
        assert_eq!(
            parse_event_type("PermissionRequest"),
            EventType::PermissionRequest
        );
        assert_eq!(parse_event_type("PreCompact"), EventType::PreCompact);
        assert_eq!(parse_event_type("Stop"), EventType::Stop);
        assert_eq!(parse_event_type("SubagentStop"), EventType::SubagentStop);
        assert_eq!(parse_event_type("Notification"), EventType::Notification);
        assert_eq!(
            parse_event_type("UserPromptSubmit"),
            EventType::UserPromptSubmit
        );
    }

    #[test]
    fn test_event_type_parse_case_insensitive() {
        assert_eq!(parse_event_type("sessionstart"), EventType::SessionStart);
        assert_eq!(parse_event_type("SESSIONSTART"), EventType::SessionStart);
        assert_eq!(parse_event_type("SessionSTART"), EventType::SessionStart);
        assert_eq!(parse_event_type("pretooluse"), EventType::PreToolUse);
        assert_eq!(
            parse_event_type("USERPROMPTSUBMIT"),
            EventType::UserPromptSubmit
        );
    }

    #[test]
    fn test_event_type_parse_unknown_becomes_custom() {
        let unknown = parse_event_type("FutureEventType");
        assert_eq!(unknown, EventType::Custom("FutureEventType".to_string()));

        let custom = parse_event_type("MyCustomEvent");
        assert_eq!(custom, EventType::Custom("MyCustomEvent".to_string()));
    }

    #[test]
    fn test_event_type_parse_trims_whitespace() {
        // Leading/trailing whitespace should be trimmed for known types
        assert_eq!(parse_event_type(" SessionStart "), EventType::SessionStart);
        assert_eq!(parse_event_type("\tPreToolUse\n"), EventType::PreToolUse);
        // Custom types also get trimmed
        assert_eq!(
            parse_event_type("  CustomEvent  "),
            EventType::Custom("CustomEvent".to_string())
        );
    }

    #[test]
    fn test_event_type_display() {
        assert_eq!(EventType::SessionStart.to_string(), "SessionStart");
        assert_eq!(EventType::PreToolUse.to_string(), "PreToolUse");
        assert_eq!(
            EventType::Custom("MyEvent".to_string()).to_string(),
            "MyEvent"
        );
    }

    #[test]
    fn test_event_type_as_str() {
        assert_eq!(EventType::SessionStart.as_str(), "SessionStart");
        assert_eq!(EventType::Custom("Test".to_string()).as_str(), "Test");
    }

    #[test]
    fn test_event_type_is_known() {
        assert!(EventType::SessionStart.is_known());
        assert!(EventType::PreToolUse.is_known());
        assert!(!EventType::Custom("Unknown".to_string()).is_known());
    }

    #[test]
    fn test_event_type_serialize() -> Result<(), String> {
        let session_start =
            serde_json::to_string(&EventType::SessionStart).map_err(|e| e.to_string())?;
        assert_eq!(session_start, r#""SessionStart""#);

        let custom = serde_json::to_string(&EventType::Custom("MyEvent".to_string()))
            .map_err(|e| e.to_string())?;
        assert_eq!(custom, r#""MyEvent""#);
        Ok(())
    }

    #[test]
    fn test_event_type_deserialize() -> Result<(), String> {
        let session_start: EventType =
            serde_json::from_str(r#""SessionStart""#).map_err(|e| e.to_string())?;
        assert_eq!(session_start, EventType::SessionStart);

        let unknown: EventType =
            serde_json::from_str(r#""FutureEvent""#).map_err(|e| e.to_string())?;
        assert_eq!(unknown, EventType::Custom("FutureEvent".to_string()));
        Ok(())
    }

    #[test]
    fn test_event_type_roundtrip() -> Result<(), String> {
        let original = EventType::PreToolUse;
        let json = serde_json::to_string(&original).map_err(|e| e.to_string())?;
        let parsed: EventType = serde_json::from_str(&json).map_err(|e| e.to_string())?;
        assert_eq!(original, parsed);

        let custom = EventType::Custom("SpecialEvent".to_string());
        let json = serde_json::to_string(&custom).map_err(|e| e.to_string())?;
        let parsed: EventType = serde_json::from_str(&json).map_err(|e| e.to_string())?;
        assert_eq!(custom, parsed);
        Ok(())
    }

    // --- EventBuilder tests ---

    #[test]
    fn test_event_builder_basic() {
        let event = EventBuilder::new("machine-1", EventType::SessionStart, "session-123").build();

        assert_eq!(event.machine_id, "machine-1");
        assert_eq!(event.event_type, EventType::SessionStart);
        assert_eq!(event.session_id, "session-123");
        assert!(event.id.is_none());
    }

    #[test]
    fn test_event_builder_impl_into_string() {
        // Test that impl Into<String> works with &str
        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
            .framework("claude")
            .model("claude-3-opus")
            .build();

        assert_eq!(event.framework, Some("claude".to_string()));
        assert_eq!(event.model, Some("claude-3-opus".to_string()));
    }

    #[test]
    fn test_event_builder_tokens() {
        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
            .tokens(1000, 500)
            .build();

        assert_eq!(event.tokens_input, Some(1000));
        assert_eq!(event.tokens_output, Some(500));
    }

    #[test]
    fn test_event_builder_cache_tokens() {
        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
            .cache_tokens(200, 100)
            .build();

        assert_eq!(event.tokens_cache_read, Some(200));
        assert_eq!(event.tokens_cache_creation, Some(100));
    }

    #[test]
    fn test_event_builder_tool() {
        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
            .tool("toolu_123", "Bash")
            .build();

        assert_eq!(event.tool_use_id, Some("toolu_123".to_string()));
        assert_eq!(event.tool_name, Some("Bash".to_string()));
    }

    #[test]
    fn test_event_builder_all_fields() {
        let ts = Utc::now();
        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
            .framework("claude")
            .model("claude-3-opus")
            .tokens(1000, 500)
            .cache_tokens(200, 100)
            .cost(0.05)
            .duration_ms(1234)
            .timestamp(ts)
            .payload(r#"{"key": "value"}"#)
            .metadata(r#"{"extra": "data"}"#)
            .build();

        assert_eq!(event.framework, Some("claude".to_string()));
        assert_eq!(event.model, Some("claude-3-opus".to_string()));
        assert_eq!(event.tokens_input, Some(1000));
        assert_eq!(event.tokens_output, Some(500));
        assert_eq!(event.tokens_cache_read, Some(200));
        assert_eq!(event.tokens_cache_creation, Some(100));
        assert_eq!(event.cost_usd, Some(0.05));
        assert_eq!(event.duration_ms, Some(1234));
        assert_eq!(event.timestamp, ts);
        assert_eq!(event.payload, Some(r#"{"key": "value"}"#.to_string()));
        assert_eq!(event.metadata, Some(r#"{"extra": "data"}"#.to_string()));
    }

    #[test]
    fn test_event_builder_opt_methods_with_some() {
        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
            .tool_use_id_opt(Some("toolu_123".to_string()))
            .tool_name_opt(Some("Bash".to_string()))
            .spawned_agent_id_opt(Some("agent-456".to_string()))
            .subagent_type_opt(Some("Explore".to_string()))
            .permission_mode_opt(Some("default".to_string()))
            .transcript_path_opt(Some("/path/to/transcript".to_string()))
            .cwd_opt(Some("/home/user".to_string()))
            .pid_opt(Some(12345))
            .build();

        assert_eq!(event.tool_use_id, Some("toolu_123".to_string()));
        assert_eq!(event.tool_name, Some("Bash".to_string()));
        assert_eq!(event.spawned_agent_id, Some("agent-456".to_string()));
        assert_eq!(event.subagent_type, Some("Explore".to_string()));
        assert_eq!(event.permission_mode, Some("default".to_string()));
        assert_eq!(
            event.transcript_path,
            Some("/path/to/transcript".to_string())
        );
        assert_eq!(event.cwd, Some("/home/user".to_string()));
        assert_eq!(event.pid, Some(12345));
    }

    #[test]
    fn test_event_builder_opt_methods_with_none() {
        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
            .tool_use_id_opt(None)
            .tool_name_opt(None)
            .spawned_agent_id_opt(None)
            .subagent_type_opt(None)
            .permission_mode_opt(None)
            .transcript_path_opt(None)
            .cwd_opt(None)
            .pid_opt(None)
            .build();

        assert!(event.tool_use_id.is_none());
        assert!(event.tool_name.is_none());
        assert!(event.spawned_agent_id.is_none());
        assert!(event.subagent_type.is_none());
        assert!(event.permission_mode.is_none());
        assert!(event.transcript_path.is_none());
        assert!(event.cwd.is_none());
        assert!(event.pid.is_none());
    }

    #[test]
    fn test_event_builder_timestamp_opt_none_keeps_current() {
        let event = EventBuilder::new("machine", EventType::SessionStart, "session")
            .timestamp_opt(None)
            .build();

        // timestamp_opt(None) should keep the timestamp set during new()
        // Just verify timestamp is set (it will be close to now)
        assert!(event.timestamp.timestamp() > 0);
    }

    #[test]
    fn test_event_builder_timestamp_opt_some() {
        let ts = Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap();
        let event = EventBuilder::new("machine", EventType::SessionStart, "session")
            .timestamp_opt(Some(ts))
            .build();

        assert_eq!(event.timestamp, ts);
    }

    #[test]
    fn test_event_builder_api_request_opt_fields() {
        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
            .tokens_cache_read_opt(Some(500))
            .tokens_cache_creation_opt(Some(100))
            .cost_opt(Some(0.03))
            .duration_ms_opt(Some(2000))
            .model_opt(Some("claude-3-sonnet".to_string()))
            .metadata_opt(Some(r#"{"foo": "bar"}"#.to_string()))
            .payload_opt(Some(r#"{"input": "test"}"#.to_string()))
            .build();

        assert_eq!(event.tokens_cache_read, Some(500));
        assert_eq!(event.tokens_cache_creation, Some(100));
        assert_eq!(event.cost_usd, Some(0.03));
        assert_eq!(event.duration_ms, Some(2000));
        assert_eq!(event.model, Some("claude-3-sonnet".to_string()));
        assert_eq!(event.metadata, Some(r#"{"foo": "bar"}"#.to_string()));
        assert_eq!(event.payload, Some(r#"{"input": "test"}"#.to_string()));
    }

    #[test]
    fn test_event_builder_payload_opt_preserves_value() {
        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
            .payload(r#"{"original": true}"#)
            .payload_opt(None) // Should preserve original value
            .build();

        assert_eq!(event.payload, Some(r#"{"original": true}"#.to_string()));
    }

    #[test]
    fn test_event_builder_individual_setters() {
        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
            .tool_use_id("toolu_abc")
            .tool_name("Read")
            .spawned_agent_id("agent-xyz")
            .subagent_type("Plan")
            .permission_mode("acceptEdits")
            .transcript_path("/tmp/transcript.jsonl")
            .cwd("/workspace")
            .pid(9999)
            .build();

        assert_eq!(event.tool_use_id, Some("toolu_abc".to_string()));
        assert_eq!(event.tool_name, Some("Read".to_string()));
        assert_eq!(event.spawned_agent_id, Some("agent-xyz".to_string()));
        assert_eq!(event.subagent_type, Some("Plan".to_string()));
        assert_eq!(event.permission_mode, Some("acceptEdits".to_string()));
        assert_eq!(
            event.transcript_path,
            Some("/tmp/transcript.jsonl".to_string())
        );
        assert_eq!(event.cwd, Some("/workspace".to_string()));
        assert_eq!(event.pid, Some(9999));
    }
}