cloacina-macros 0.9.0

Procedural macros for the cloacina workflow orchestration library.
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
1105
/*
 *  Copyright 2025-2026 Colliery Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use syn::{
    parse::{Parse, ParseStream},
    Expr, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, PathArguments, Result as SynResult,
    ReturnType, Token, Type,
};

use crate::registry::{get_registry, TaskInfo};

/// Attributes for the task macro that define task behavior and configuration
///
/// # Fields
///
/// * `id` - Unique identifier for the task (required)
/// * `dependencies` - List of task IDs this task depends on
/// * `retry_attempts` - Maximum number of retry attempts (default: 3)
/// * `retry_backoff` - Backoff strategy: "fixed", "linear", or "exponential" (default: "exponential")
/// * `retry_delay_ms` - Initial delay between retries in milliseconds (default: 1000)
/// * `retry_max_delay_ms` - Maximum delay between retries in milliseconds (default: 30000)
/// * `retry_condition` - Condition for retrying: "never", "all", "transient", or error patterns
/// * `retry_jitter` - Whether to add random jitter to retry delays (default: true)
/// * `trigger_rules` - Rules that determine when the task should be executed
/// * `on_success` - Function to call on successful task completion: `async fn(&str, &Context<Value>)`
/// * `on_failure` - Function to call on task failure: `async fn(&str, &TaskError, &Context<Value>)`
#[derive(Default)]
pub struct TaskAttributes {
    pub id: String,
    pub dependencies: Vec<String>, // Will need to convert to TaskNamespace during code generation
    pub retry_attempts: Option<i32>,
    pub retry_backoff: Option<String>,
    pub retry_delay_ms: Option<i32>,
    pub retry_max_delay_ms: Option<i32>,
    pub retry_condition: Option<String>,
    pub retry_jitter: Option<bool>,
    pub trigger_rules: Option<Expr>,
    pub on_success: Option<Expr>,
    pub on_failure: Option<Expr>,
    /// Optional `invokes = computation_graph("name")` clause. Set when the
    /// task wraps a trigger-less computation graph; the macro emits an
    /// invocation body that resolves the graph at runtime by walking
    /// `inventory::iter::<TriggerlessGraphEntry>` for `name`, then routes
    /// terminal outputs back into the task's context. The compile-time
    /// `<H as TriggerlessGraph>` trait-bound check from T-0540 M3 is gone —
    /// runtime contract validation at load time (T-B) is the replacement.
    pub invokes_computation_graph: Option<String>,
    /// Optional `post_invocation = fn_name` callback. Only meaningful with
    /// `invokes`: the named async fn runs after the graph has fired and its
    /// terminal outputs have been routed into the context, but before
    /// `on_success`. Signature: `async fn(&mut Context<Value>) -> Result<(),
    /// TaskError>`. Lets the user inspect the merged context (graph
    /// outputs + pre-work additions) and react before the task is finalized.
    pub post_invocation: Option<Expr>,
}

impl Parse for TaskAttributes {
    fn parse(input: ParseStream) -> SynResult<Self> {
        let mut id = None;
        let mut dependencies = Vec::new();
        let mut retry_attempts = None;
        let mut retry_backoff = None;
        let mut retry_delay_ms = None;
        let mut retry_max_delay_ms = None;
        let mut retry_condition = None;
        let mut retry_jitter = None;
        let mut trigger_rules = None;
        let mut on_success = None;
        let mut on_failure = None;
        let mut invokes_computation_graph: Option<String> = None;
        let mut post_invocation: Option<Expr> = None;

        while !input.is_empty() {
            let name: Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match name.to_string().as_str() {
                "id" => {
                    let lit: LitStr = input.parse()?;
                    id = Some(lit.value());
                }
                "dependencies" => {
                    // Parse array of strings: ["dep1", "dep2"]
                    let content;
                    syn::bracketed!(content in input);

                    while !content.is_empty() {
                        let lit: LitStr = content.parse()?;
                        dependencies.push(lit.value());

                        if !content.is_empty() {
                            content.parse::<Token![,]>()?;
                        }
                    }
                }
                "retry_attempts" => {
                    let lit: syn::LitInt = input.parse()?;
                    retry_attempts = Some(lit.base10_parse()?);
                }
                "retry_backoff" => {
                    let lit: LitStr = input.parse()?;
                    retry_backoff = Some(lit.value());
                }
                "retry_delay_ms" => {
                    let lit: syn::LitInt = input.parse()?;
                    retry_delay_ms = Some(lit.base10_parse()?);
                }
                "retry_max_delay_ms" => {
                    let lit: syn::LitInt = input.parse()?;
                    retry_max_delay_ms = Some(lit.base10_parse()?);
                }
                "retry_condition" => {
                    let lit: LitStr = input.parse()?;
                    retry_condition = Some(lit.value());
                }
                "retry_jitter" => {
                    let lit: syn::LitBool = input.parse()?;
                    retry_jitter = Some(lit.value);
                }
                "trigger_rules" => {
                    let expr: Expr = input.parse()?;
                    trigger_rules = Some(expr);
                }
                "on_success" => {
                    let expr: Expr = input.parse()?;
                    on_success = Some(expr);
                }
                "on_failure" => {
                    let expr: Expr = input.parse()?;
                    on_failure = Some(expr);
                }
                "invokes" => {
                    if invokes_computation_graph.is_some() {
                        return Err(syn::Error::new(name.span(), "duplicate 'invokes' field"));
                    }
                    let kind: Ident = input.parse()?;
                    if kind != "computation_graph" {
                        return Err(syn::Error::new(
                            kind.span(),
                            format!(
                                "unknown invokes kind '{}', expected 'computation_graph' \
                                 (e.g. invokes = computation_graph(\"my_graph\"))",
                                kind
                            ),
                        ));
                    }
                    let paren;
                    syn::parenthesized!(paren in input);
                    let lit: LitStr = paren.parse().map_err(|_| {
                        syn::Error::new(
                            paren.span(),
                            "computation_graph(...) expects a string-literal name \
                             (e.g. computation_graph(\"my_graph\")). The type-path form \
                             was removed in CLOACI-I-0102 — graphs are referenced by \
                             name with runtime contract validation.",
                        )
                    })?;
                    if !paren.is_empty() {
                        return Err(syn::Error::new(
                            paren.span(),
                            "computation_graph(...) takes exactly one string-literal argument",
                        ));
                    }
                    invokes_computation_graph = Some(lit.value());
                }
                "post_invocation" => {
                    if post_invocation.is_some() {
                        return Err(syn::Error::new(
                            name.span(),
                            "duplicate 'post_invocation' field",
                        ));
                    }
                    let expr: Expr = input.parse()?;
                    post_invocation = Some(expr);
                }
                _ => {
                    return Err(syn::Error::new(
                        name.span(),
                        format!("Unknown attribute: {}", name),
                    ));
                }
            }

            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        // `id` is optional (CLOACI-T-0732): when omitted it defaults to the
        // function name. The default is resolved at expansion time where the fn
        // ident is available (an empty string here is the "not provided" sentinel).
        let id = id.unwrap_or_default();

        Ok(TaskAttributes {
            id,
            dependencies,
            retry_attempts,
            retry_backoff,
            retry_delay_ms,
            retry_max_delay_ms,
            retry_condition,
            retry_jitter,
            trigger_rules,
            on_success,
            on_failure,
            invokes_computation_graph,
            post_invocation,
        })
    }
}

/// Calculate code fingerprint from function
///
/// Generates a unique hash based on the function's signature and body.
/// This is used for detecting changes in task implementations.
///
/// # Arguments
///
/// * `func` - The function to calculate the fingerprint for
///
/// # Returns
///
/// A hexadecimal string representing the function's fingerprint
pub fn calculate_function_fingerprint(func: &ItemFn) -> String {
    let mut hasher = DefaultHasher::new();

    // Hash function signature (excluding name)
    func.sig.inputs.iter().for_each(|input| {
        if let syn::FnArg::Typed(pat_type) = input {
            quote::quote!(#pat_type).to_string().hash(&mut hasher);
        }
    });

    // Hash return type
    quote::quote!(#(&func.sig.output))
        .to_string()
        .hash(&mut hasher);

    // Hash function body (this is the key part for detecting changes)
    let body_tokens = quote::quote!(#(&func.block)).to_string();
    body_tokens.hash(&mut hasher);

    // Include async info
    func.sig.asyncness.is_some().hash(&mut hasher);

    format!("{:016x}", hasher.finish())
}

/// Generate retry policy creation code based on task attributes
///
/// # Arguments
///
/// * `attrs` - The task attributes containing retry policy configuration
///
/// # Returns
///
/// A `TokenStream2` containing the generated code for retry policy creation
pub fn generate_retry_policy_code(attrs: &TaskAttributes) -> TokenStream2 {
    let max_attempts = attrs.retry_attempts.unwrap_or(3);
    let initial_delay_ms = attrs.retry_delay_ms.unwrap_or(1000);
    let max_delay_ms = attrs.retry_max_delay_ms.unwrap_or(30000);
    let with_jitter = attrs.retry_jitter.unwrap_or(true);

    // Generate backoff strategy
    // Use absolute path ::cloacina_workflow to work with both direct dependencies
    // and indirect dependencies through cloacina's re-export
    let backoff_strategy = match attrs.retry_backoff.as_deref() {
        Some("fixed") => quote! {
            ::cloacina_workflow::BackoffStrategy::Fixed
        },
        Some("linear") => quote! {
            ::cloacina_workflow::BackoffStrategy::Linear { multiplier: 1.0 }
        },
        Some("exponential") | None => quote! {
            ::cloacina_workflow::BackoffStrategy::Exponential { base: 2.0, multiplier: 1.0 }
        },
        Some(_other) => {
            // Custom backoff - for now, default to exponential
            quote! {
                ::cloacina_workflow::BackoffStrategy::Exponential { base: 2.0, multiplier: 1.0 }
            }
        }
    };

    // Generate retry condition
    let retry_condition = match attrs.retry_condition.as_deref() {
        Some("never") => quote! {
            vec![::cloacina_workflow::RetryCondition::Never]
        },
        Some("all") | None => quote! {
            vec![::cloacina_workflow::RetryCondition::AllErrors]
        },
        Some("transient") => quote! {
            vec![::cloacina_workflow::RetryCondition::TransientOnly]
        },
        Some(patterns) => {
            // Parse comma-separated patterns
            let pattern_list: Vec<&str> = patterns.split(',').map(|s| s.trim()).collect();
            quote! {
                vec![::cloacina_workflow::RetryCondition::ErrorPattern {
                    patterns: vec![#(#pattern_list.to_string()),*]
                }]
            }
        }
    };

    quote! {
        ::cloacina_workflow::RetryPolicy {
            max_attempts: #max_attempts,
            initial_delay: std::time::Duration::from_millis(#initial_delay_ms as u64),
            max_delay: std::time::Duration::from_millis(#max_delay_ms as u64),
            backoff_strategy: #backoff_strategy,
            retry_conditions: #retry_condition,
            jitter: #with_jitter,
        }
    }
}

/// Generate trigger rules JSON code based on task attributes
///
/// # Arguments
///
/// * `attrs` - The task attributes containing trigger rules configuration
///
/// # Returns
///
/// A `TokenStream2` containing the generated code for trigger rules
pub fn generate_trigger_rules_code(attrs: &TaskAttributes) -> TokenStream2 {
    match &attrs.trigger_rules {
        Some(expr) => match parse_trigger_rules_expr(expr) {
            Ok(json_value) => {
                let json_string = json_value.to_string();
                quote! {
                    serde_json::from_str(#json_string).unwrap()
                }
            }
            Err(error) => {
                let error_msg = format!("Invalid trigger rule: {}", error);
                quote! {
                    compile_error!(#error_msg)
                }
            }
        },
        None => {
            // Default to Always
            quote! {
                serde_json::json!({"type": "Always"})
            }
        }
    }
}

/// Parse trigger rule expressions into JSON at compile time
///
/// # Arguments
///
/// * `expr` - The trigger rule expression to parse
///
/// # Returns
///
/// A `Result` containing either the parsed JSON value or an error message
///
/// # Supported Rules
///
/// * Simple rules: `always`
/// * Composite rules: `all()`, `any()`, `none()`
/// * Task status rules: `task_success()`, `task_failed()`, `task_skipped()`
/// * Context rules: `context_value()`
pub fn parse_trigger_rules_expr(expr: &Expr) -> Result<serde_json::Value, String> {
    match expr {
        // Handle simple identifiers like 'always'
        Expr::Path(path) => {
            if let Some(ident) = path.path.get_ident() {
                match ident.to_string().as_str() {
                    "always" => Ok(serde_json::json!({"type": "Always"})),
                    _ => Err(format!("Unknown trigger rule: {}", ident)),
                }
            } else {
                Err("Invalid trigger rule path".to_string())
            }
        }
        // Handle function calls like all(), any(), none(), task_success(), etc.
        Expr::Call(call) => {
            if let Expr::Path(path) = &*call.func {
                if let Some(ident) = path.path.get_ident() {
                    match ident.to_string().as_str() {
                        "all" => {
                            let conditions = parse_condition_list(&call.args)?;
                            Ok(serde_json::json!({"type": "All", "conditions": conditions}))
                        }
                        "any" => {
                            let conditions = parse_condition_list(&call.args)?;
                            Ok(serde_json::json!({"type": "Any", "conditions": conditions}))
                        }
                        "none" => {
                            let conditions = parse_condition_list(&call.args)?;
                            Ok(serde_json::json!({"type": "None", "conditions": conditions}))
                        }
                        "task_success" => {
                            if call.args.len() != 1 {
                                return Err(
                                    "task_success requires exactly one argument".to_string()
                                );
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            let condition =
                                serde_json::json!({"type": "TaskSuccess", "task_name": task_name});
                            Ok(serde_json::json!({"type": "All", "conditions": [condition]}))
                        }
                        "task_failed" => {
                            if call.args.len() != 1 {
                                return Err("task_failed requires exactly one argument".to_string());
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            let condition =
                                serde_json::json!({"type": "TaskFailed", "task_name": task_name});
                            Ok(serde_json::json!({"type": "All", "conditions": [condition]}))
                        }
                        "task_skipped" => {
                            if call.args.len() != 1 {
                                return Err(
                                    "task_skipped requires exactly one argument".to_string()
                                );
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            let condition =
                                serde_json::json!({"type": "TaskSkipped", "task_name": task_name});
                            Ok(serde_json::json!({"type": "All", "conditions": [condition]}))
                        }
                        "context_value" => {
                            if call.args.len() != 3 {
                                return Err("context_value requires exactly three arguments: key, operator, value".to_string());
                            }
                            let key = extract_string_literal(&call.args[0])?;
                            let operator = parse_value_operator(&call.args[1])?;
                            let value = parse_json_value(&call.args[2])?;
                            let condition = serde_json::json!({
                                "type": "ContextValue",
                                "key": key,
                                "operator": operator,
                                "value": value
                            });
                            Ok(serde_json::json!({"type": "All", "conditions": [condition]}))
                        }
                        _ => Err(format!("Unknown trigger rule function: {}", ident)),
                    }
                } else {
                    Err("Invalid trigger rule function".to_string())
                }
            } else {
                Err("Invalid trigger rule call".to_string())
            }
        }
        _ => Err("Unsupported trigger rule expression".to_string()),
    }
}

/// Parse a list of trigger conditions from function arguments
fn parse_condition_list(
    args: &syn::punctuated::Punctuated<Expr, syn::Token![,]>,
) -> Result<Vec<serde_json::Value>, String> {
    let mut conditions = Vec::new();
    for arg in args {
        conditions.push(parse_trigger_condition_expr(arg)?);
    }
    Ok(conditions)
}

/// Parse a single trigger condition (not wrapped in a rule)
fn parse_trigger_condition_expr(expr: &Expr) -> Result<serde_json::Value, String> {
    match expr {
        Expr::Call(call) => {
            if let Expr::Path(path) = &*call.func {
                if let Some(ident) = path.path.get_ident() {
                    match ident.to_string().as_str() {
                        "task_success" => {
                            if call.args.len() != 1 {
                                return Err(
                                    "task_success requires exactly one argument".to_string()
                                );
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            Ok(serde_json::json!({"type": "TaskSuccess", "task_name": task_name}))
                        }
                        "task_failed" => {
                            if call.args.len() != 1 {
                                return Err("task_failed requires exactly one argument".to_string());
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            Ok(serde_json::json!({"type": "TaskFailed", "task_name": task_name}))
                        }
                        "task_skipped" => {
                            if call.args.len() != 1 {
                                return Err(
                                    "task_skipped requires exactly one argument".to_string()
                                );
                            }
                            let task_name = extract_string_literal(&call.args[0])?;
                            Ok(serde_json::json!({"type": "TaskSkipped", "task_name": task_name}))
                        }
                        "context_value" => {
                            if call.args.len() != 3 {
                                return Err("context_value requires exactly three arguments: key, operator, value".to_string());
                            }
                            let key = extract_string_literal(&call.args[0])?;
                            let operator = parse_value_operator(&call.args[1])?;
                            let value = parse_json_value(&call.args[2])?;
                            Ok(serde_json::json!({
                                "type": "ContextValue",
                                "key": key,
                                "operator": operator,
                                "value": value
                            }))
                        }
                        _ => Err(format!("Unknown trigger condition function: {}", ident)),
                    }
                } else {
                    Err("Invalid trigger condition function".to_string())
                }
            } else {
                Err("Invalid trigger condition call".to_string())
            }
        }
        _ => Err("Unsupported trigger condition expression".to_string()),
    }
}

/// Extract a string literal from an expression
fn extract_string_literal(expr: &Expr) -> Result<String, String> {
    match expr {
        Expr::Lit(lit) => {
            if let syn::Lit::Str(lit_str) = &lit.lit {
                Ok(lit_str.value())
            } else {
                Err("Expected string literal".to_string())
            }
        }
        _ => Err("Expected string literal".to_string()),
    }
}

/// Parse value operators like equals, greater_than, etc.
fn parse_value_operator(expr: &Expr) -> Result<String, String> {
    match expr {
        Expr::Path(path) => {
            if let Some(ident) = path.path.get_ident() {
                match ident.to_string().as_str() {
                    "equals" => Ok("Equals".to_string()),
                    "not_equals" => Ok("NotEquals".to_string()),
                    "greater_than" => Ok("GreaterThan".to_string()),
                    "less_than" => Ok("LessThan".to_string()),
                    "contains" => Ok("Contains".to_string()),
                    "not_contains" => Ok("NotContains".to_string()),
                    "exists" => Ok("Exists".to_string()),
                    "not_exists" => Ok("NotExists".to_string()),
                    _ => Err(format!("Unknown operator: {}", ident)),
                }
            } else {
                Err("Invalid operator path".to_string())
            }
        }
        _ => Err("Expected operator identifier".to_string()),
    }
}

/// Parse JSON values from expressions
fn parse_json_value(expr: &Expr) -> Result<serde_json::Value, String> {
    match expr {
        Expr::Lit(lit) => match &lit.lit {
            syn::Lit::Str(s) => Ok(serde_json::Value::String(s.value())),
            syn::Lit::Int(i) => {
                let value: i64 = i
                    .base10_parse()
                    .map_err(|e| format!("Invalid integer: {}", e))?;
                Ok(serde_json::Value::Number(serde_json::Number::from(value)))
            }
            syn::Lit::Float(f) => {
                let value: f64 = f
                    .base10_parse()
                    .map_err(|e| format!("Invalid float: {}", e))?;
                Ok(serde_json::Value::Number(
                    serde_json::Number::from_f64(value)
                        .ok_or_else(|| "Invalid float value".to_string())?,
                ))
            }
            syn::Lit::Bool(b) => Ok(serde_json::Value::Bool(b.value)),
            _ => Err("Unsupported literal type".to_string()),
        },
        _ => Err("Expected literal value".to_string()),
    }
}

/// Convert snake_case to PascalCase
///
/// # Arguments
///
/// * `s` - The string to convert
///
/// # Returns
///
/// The converted string in PascalCase
pub fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

/// Generate the task implementation
///
/// Creates the task struct, implementation, and registration code based on
/// the provided attributes and function.
///
/// # Arguments
///
/// * `attrs` - The task attributes
/// * `input` - The input function to be wrapped as a task
///
/// # Returns
///
/// A `TokenStream2` containing the generated task implementation
/// Normalize a task function's return type so authors can write a bare
/// `-> Result<()>` (or `-> Result<T>`) and have the error type default to
/// `TaskError` (CLOACI-T-0734). A return type that is a single-argument
/// `Result<T>` is rewritten to `Result<T, ::cloacina_workflow::TaskError>`;
/// anything else (already two-arg `Result<T, E>`, `-> ()`, no return, etc.) is
/// emitted verbatim, so this is purely additive.
fn normalize_task_return_type(output: &ReturnType) -> TokenStream2 {
    if let ReturnType::Type(arrow, ty) = output {
        if let Type::Path(type_path) = &**ty {
            if let Some(seg) = type_path.path.segments.last() {
                if seg.ident == "Result" {
                    if let PathArguments::AngleBracketed(args) = &seg.arguments {
                        // Count only type arguments (ignore lifetimes etc.).
                        let type_args: Vec<&GenericArgument> = args
                            .args
                            .iter()
                            .filter(|a| matches!(a, GenericArgument::Type(_)))
                            .collect();
                        if type_args.len() == 1 {
                            let ok_ty = type_args[0];
                            return quote! {
                                #arrow ::std::result::Result<#ok_ty, ::cloacina_workflow::TaskError>
                            };
                        }
                    }
                }
            }
        }
    }
    quote! { #output }
}

pub fn generate_task_impl(attrs: TaskAttributes, input: ItemFn) -> TokenStream2 {
    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_block = &input.block;
    let fn_inputs = &input.sig.inputs;
    let fn_output = &input.sig.output;
    // Bare `-> Result<()>` → `-> Result<(), TaskError>` (CLOACI-T-0734).
    let normalized_output = normalize_task_return_type(fn_output);
    let fn_asyncness = &input.sig.asyncness;

    // Calculate code fingerprint
    let code_fingerprint = calculate_function_fingerprint(&input);

    // Extract context parameter
    let context_param = fn_inputs.iter().find_map(|arg| {
        if let FnArg::Typed(pat_type) = arg {
            if let Pat::Ident(pat_ident) = &*pat_type.pat {
                let param_name = pat_ident.ident.to_string();
                if param_name == "context"
                    || param_name == "_context"
                    || param_name.starts_with("context")
                {
                    return Some(&*pat_type.ty);
                }
            }
        }
        None
    });

    // Validate function signature
    if context_param.is_none() {
        return quote! {
            compile_error!("Task function must have a 'context' parameter (can be named 'context' or '_context')");
        };
    }

    // Detect optional TaskHandle parameter (second parameter named "handle" or "task_handle")
    let has_handle_param = fn_inputs.iter().any(|arg| {
        if let FnArg::Typed(pat_type) = arg {
            if let Pat::Ident(pat_ident) = &*pat_type.pat {
                let param_name = pat_ident.ident.to_string();
                return param_name == "handle" || param_name == "task_handle";
            }
        }
        false
    });

    let task_struct_name = syn::Ident::new(
        &format!("{}Task", to_pascal_case(&fn_name.to_string())),
        fn_name.span(),
    );

    let task_id = &attrs.id;
    let dependencies = &attrs.dependencies;

    // Generate retry policy creation code
    let generate_retry_policy = generate_retry_policy_code(&attrs);

    // Generate trigger rules JSON code
    let generate_trigger_rules = generate_trigger_rules_code(&attrs);

    let execute_body = match (fn_asyncness.is_some(), has_handle_param) {
        (true, true) => quote! {
            {
                let mut handle = ::cloacina::take_task_handle();
                let result = #fn_name(&mut context, &mut handle).await;
                ::cloacina::return_task_handle(handle);
                result
            }
        },
        (true, false) => quote! {
            #fn_name(&mut context).await
        },
        (false, true) => quote! {
            {
                let mut handle = ::cloacina::take_task_handle();
                let result = #fn_name(&mut context, &mut handle);
                ::cloacina::return_task_handle(handle);
                result
            }
        },
        (false, false) => quote! {
            #fn_name(&mut context)
        },
    };

    // Create a task constructor function name
    let task_constructor_name = syn::Ident::new(&format!("{}_task", fn_name), fn_name.span());

    // Generate callback invocation code
    // on_success signature: async fn(task_id: &str, context: &Context<Value>)
    let on_success_call = match &attrs.on_success {
        Some(callback_fn) => quote! {
            // Call on_success callback, isolating any errors
            if let Err(callback_err) = #callback_fn(#task_id, &context).await {
                eprintln!("[cloacina] on_success callback failed for task '{}': {:?}", #task_id, callback_err);
            }
        },
        None => quote! {},
    };

    // on_failure signature: async fn(task_id: &str, error: &TaskError, context: &Context<Value>)
    let on_failure_call = match &attrs.on_failure {
        Some(callback_fn) => quote! {
            // Call on_failure callback, isolating any errors
            if let Err(callback_err) = #callback_fn(#task_id, &task_error, &context).await {
                eprintln!("[cloacina] on_failure callback failed for task '{}': {:?}", #task_id, callback_err);
            }
        },
        None => quote! {},
    };

    // When `invokes = computation_graph(H)` is set, the macro emits an extra
    // step that runs after the user body (pre-work) and:
    //
    // 1. Pulls the compiled fn off the handle through `<H as
    //    ::cloacina::TriggerlessGraph>::compiled_fn()`. Reactor-triggered
    //    graphs do not implement `TriggerlessGraph`; binding to one fails to
    //    compile with "trait not implemented" — the compile-time gate the
    //    AC requires.
    // 2. Invokes the graph with a clone of the task's context.
    // 3. On Completed, zips terminal node names with the typed-erased
    //    outputs (which the trigger-less codegen pre-serialized to
    //    `serde_json::Value` at the terminal site) and routes each into the
    //    output context under its terminal name.
    // 4. On Error, surfaces the GraphError as a `TaskError::ExecutionFailed`.
    // Optional post-invocation hook. Runs after the graph fires and its
    // outputs have been routed into the context, before `on_success`. Only
    // meaningful when `invokes` is set; when `invokes` is unset and the
    // user supplies `post_invocation`, the macro errors at expansion.
    if attrs.post_invocation.is_some() && attrs.invokes_computation_graph.is_none() {
        return quote! {
            compile_error!("`post_invocation` requires `invokes = computation_graph(...)` to be set");
        };
    }
    let post_invocation_call = match &attrs.post_invocation {
        Some(callback_fn) => quote! {
            if let Err(post_err) = #callback_fn(&mut context).await {
                let task_error = ::cloacina_workflow::TaskError::ExecutionFailed {
                    message: format!("post_invocation callback failed: {:?}", post_err),
                    task_id: #task_id.to_string(),
                    timestamp: chrono::Utc::now(),
                };
                #on_failure_call
                return Err(task_error);
            }
        },
        None => quote! {},
    };

    let graph_invocation = match &attrs.invokes_computation_graph {
        Some(graph_name) => {
            let graph_name_lit = graph_name.clone();
            quote! {
                {
                    // I-0102 / T-A: graphs are referenced by string name. Walk
                    // the runtime-collected `TriggerlessGraphEntry` inventory
                    // to resolve the named graph. Reactor-triggered graphs
                    // submit a `ComputationGraphEntry` instead, so a name
                    // collision would still surface as "no triggerless graph
                    // named X" — the runtime equivalent of T-0540 M3's
                    // compile-time trait-bound check.
                    //
                    // Cfg-gated path resolution: library mode goes through
                    // `cloacina::cloacina_workflow_plugin::*`, packaged
                    // cdylibs through the direct dep.
                    #[cfg(not(feature = "packaged"))]
                    let __reg_opt = ::cloacina::cloacina_workflow_plugin::inventory::iter::<::cloacina::cloacina_workflow_plugin::TriggerlessGraphEntry>
                        .into_iter()
                        .find(|e| e.name == #graph_name_lit)
                        .map(|e| (e.constructor)());
                    #[cfg(feature = "packaged")]
                    let __reg_opt = ::cloacina_workflow_plugin::inventory::iter::<::cloacina_workflow_plugin::TriggerlessGraphEntry>
                        .into_iter()
                        .find(|e| e.name == #graph_name_lit)
                        .map(|e| (e.constructor)());
                    let __reg = match __reg_opt {
                        Some(r) => r,
                        None => {
                            let task_error = ::cloacina_workflow::TaskError::ExecutionFailed {
                                message: format!(
                                    "computation_graph '{}' is not registered as a \
                                     trigger-less graph in this runtime; ensure the \
                                     package declaring it is loaded and that the graph \
                                     is declared without `trigger = reactor(...)`",
                                    #graph_name_lit,
                                ),
                                task_id: #task_id.to_string(),
                                timestamp: chrono::Utc::now(),
                            };
                            #on_failure_call
                            return Err(task_error);
                        }
                    };
                    let __graph_fn = __reg.graph_fn.clone();
                    let __terminal_names: Vec<String> = __reg.terminal_node_names.clone();
                    let __ctx_for_graph = context.clone_data();
                    let __graph_result = __graph_fn(__ctx_for_graph).await;
                    match __graph_result {
                        ::cloacina::computation_graph::GraphResult::Completed { outputs, .. } => {
                            for (idx, name) in __terminal_names.iter().enumerate() {
                                if let Some(boxed) = outputs.get(idx) {
                                    if let Some(value) =
                                        boxed.downcast_ref::<::serde_json::Value>()
                                    {
                                        if context.get(name.as_str()).is_some() {
                                            let _ = context.update(name.as_str(), value.clone());
                                        } else {
                                            let _ = context.insert(name.as_str(), value.clone());
                                        }
                                    }
                                }
                            }
                        }
                        ::cloacina::computation_graph::GraphResult::Error(graph_err) => {
                            let task_error = ::cloacina_workflow::TaskError::ExecutionFailed {
                                message: format!(
                                    "computation_graph '{}' invocation failed: {}",
                                    #graph_name_lit,
                                    graph_err,
                                ),
                                task_id: #task_id.to_string(),
                                timestamp: chrono::Utc::now(),
                            };
                            #on_failure_call
                            return Err(task_error);
                        }
                    }
                }
            }
        }
        None => quote! {},
    };

    quote! {
        // Keep the original function for testing
        #fn_vis #fn_asyncness fn #fn_name(#fn_inputs) #normalized_output #fn_block

        // Generate the task struct
        #[derive(Debug)]
        #fn_vis struct #task_struct_name {
            dependencies: Vec<::cloacina_workflow::TaskNamespace>,
        }

        impl #task_struct_name {
            pub fn new() -> Self {
                Self {
                    dependencies: Vec::new(), // Will be populated by workflow builder
                }
            }

            pub fn with_dependencies(mut self, dependencies: Vec<::cloacina_workflow::TaskNamespace>) -> Self {
                self.dependencies = dependencies;
                self
            }

            pub fn dependency_task_ids() -> &'static [&'static str] {
                &[#(#dependencies),*]
            }

            /// Get the code fingerprint for this task
            pub fn code_fingerprint() -> &'static str {
                #code_fingerprint
            }

            /// Create the retry policy based on macro attributes
            pub fn create_retry_policy(&self) -> ::cloacina_workflow::RetryPolicy {
                #generate_retry_policy
            }

            /// Get the trigger rules for this task
            pub fn trigger_rules(&self) -> serde_json::Value {
                #generate_trigger_rules
            }
        }


        #[async_trait::async_trait]
        impl ::cloacina_workflow::Task for #task_struct_name {
            async fn execute(&self, mut context: ::cloacina_workflow::Context<serde_json::Value>)
                -> Result<::cloacina_workflow::Context<serde_json::Value>, ::cloacina_workflow::TaskError> {

                // Convert the result to our expected format
                match #execute_body {
                    Ok(()) => {
                        // Optional CG invocation (no-op when `invokes` is unset).
                        #graph_invocation
                        // Optional post-invocation hook (no-op when unset).
                        #post_invocation_call
                        #on_success_call
                        Ok(context)
                    },
                    Err(e) => {
                        let task_error = ::cloacina_workflow::TaskError::ExecutionFailed {
                            message: format!("{:?}", e),
                            task_id: #task_id.to_string(),
                            timestamp: chrono::Utc::now(),
                        };
                        #on_failure_call
                        Err(task_error)
                    },
                }
            }

            fn id(&self) -> &str {
                #task_id
            }

            fn dependencies(&self) -> &[::cloacina_workflow::TaskNamespace] {
                &self.dependencies
            }

            fn retry_policy(&self) -> ::cloacina_workflow::RetryPolicy {
                self.create_retry_policy()
            }

            fn trigger_rules(&self) -> serde_json::Value {
                self.trigger_rules()
            }

            fn code_fingerprint(&self) -> Option<String> {
                Some(Self::code_fingerprint().to_string())
            }

            fn requires_handle(&self) -> bool {
                #has_handle_param
            }
        }

        // Provide a convenience function to create the task
        #fn_vis fn #task_constructor_name() -> #task_struct_name {
            #task_struct_name::new()
        }
    }
}

/// The main task proc macro
///
/// # Usage
///
/// ```rust
/// #[task(
///     id = "my_task",
///     dependencies = ["other_task"],
///     retry_attempts = 3,
///     retry_backoff = "exponential"
/// )]
/// async fn my_task(context: &mut Context<Value>) -> Result<(), TaskError> {
///     // Task implementation
///     Ok(())
/// }
/// ```
///
/// # Attributes
///
/// See `TaskAttributes` for available configuration options.
pub fn task(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = TokenStream2::from(args);
    let input = TokenStream2::from(input);

    let attrs = match syn::parse2::<TaskAttributes>(args) {
        Ok(attrs) => attrs,
        Err(e) => {
            return syn::Error::new(Span::call_site(), format!("Invalid task attributes: {}", e))
                .to_compile_error()
                .into();
        }
    };

    let input_fn = match syn::parse2::<ItemFn>(input) {
        Ok(input_fn) => input_fn,
        Err(e) => {
            return syn::Error::new(
                Span::call_site(),
                format!("Task macro can only be applied to functions: {}", e),
            )
            .to_compile_error()
            .into();
        }
    };

    // Default `id` to the function name when not explicitly provided
    // (CLOACI-T-0732). Resolved here, where both the parsed attrs and the
    // function ident are available, so a bare `#[task]` is valid.
    let attrs = {
        let mut attrs = attrs;
        if attrs.id.is_empty() {
            attrs.id = input_fn.sig.ident.to_string();
        }
        attrs
    };

    // PHASE 1: Register task in compile-time registry and validate
    // Use a timeout to avoid hanging if there are mutex issues
    let file_path = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| "unknown".to_string());

    // Note: We no longer need to check if we're in a workflow package context
    // since validation is deferred for all tasks

    let task_info = TaskInfo {
        id: attrs.id.clone(),
        dependencies: attrs.dependencies.clone(),
        file_path: file_path.clone(),
    };

    // PHASE 2: Register task and check for duplicate IDs
    let registration_result = {
        // Try to acquire the lock with a timeout approach
        match get_registry().try_lock() {
            Ok(mut registry) => {
                // Register this task - duplicate ID detection happens here
                registry.register_task(task_info)
            }
            Err(_) => {
                // If we can't acquire the lock, skip registration to avoid hanging
                // This can happen during parallel compilation
                Ok(())
            }
        }
    };

    // Emit compile error if registration failed (e.g., duplicate task ID)
    if let Err(e) = registration_result {
        return e.to_compile_error().into();
    }

    // PHASE 3: Generate the task implementation
    generate_task_impl(attrs, input_fn).into()
}