things3-core 2.0.0

Core library for Things 3 database access and data models
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
//! Pure AppleScript builders for the task operations.
//!
//! Every function here is a referentially-transparent transform from typed
//! input to AppleScript text. They do not spawn `osascript`; that is the
//! [`super::runner`] module's job. Splitting the two means the bulk of the
//! backend's logic is unit-testable on any platform without a Things 3 install.
//!
//! ## Conventions used by every script
//!
//! - Wrapped in `tell application "Things3" … end tell` so all references
//!   resolve against Things.
//! - Wrapped in `with timeout of 600 seconds … end timeout`. The default
//!   Apple Event timeout is ~120 s; Things mutations against a busy database
//!   can stall longer than that. Cheap insurance against spurious timeouts.
//! - Every interpolated user-controlled string flows through
//!   [`super::escape::as_applescript_string`]. UUIDs come from the typed
//!   [`Uuid`] which only round-trips hex+hyphens, so they are interpolated
//!   directly without escaping.
//! - Date components are assigned individually (`day` first set to 1 to dodge
//!   the May-31 → April overflow trap) instead of via the locale-sensitive
//!   `date "…"` literal.

use chrono::{Datelike, NaiveDate};

use super::escape::as_applescript_string;
use crate::models::{
    BulkCompleteRequest, BulkCreateTasksRequest, BulkDeleteRequest, BulkMoveRequest,
    BulkUpdateDatesRequest, CreateAreaRequest, CreateProjectRequest, CreateTagRequest,
    CreateTaskRequest, TaskStatus, ThingsId, UpdateAreaRequest, UpdateProjectRequest,
    UpdateTagRequest, UpdateTaskRequest,
};

/// Wrap a script body in the standard `tell application` + `with timeout`
/// envelope. `body` is appended verbatim — caller controls indentation.
fn wrap(body: &str) -> String {
    format!(
        "tell application \"Things3\"\n\
         \twith timeout of 600 seconds\n\
         {body}\
         \tend timeout\n\
         end tell\n"
    )
}

/// AppleScript snippet that assigns variable `var` to a `date` object equal to
/// `date` at midnight. Caller is responsible for the surrounding `tell` block.
///
/// The `set day of … to 1` line is deliberate: setting `month` first when the
/// current `day` is 31 (and the target month has 30 or fewer days) produces
/// silent date overflow. Setting day to 1 sidesteps that.
fn assign_date_var(var: &str, date: NaiveDate) -> String {
    format!(
        "\t\tset {var} to current date\n\
         \t\tset day of {var} to 1\n\
         \t\tset year of {var} to {year}\n\
         \t\tset month of {var} to {month}\n\
         \t\tset day of {var} to {day}\n\
         \t\tset time of {var} to 0\n",
        year = date.year(),
        month = date.month(),
        day = date.day(),
    )
}

/// Map a [`TaskStatus`] to its AppleScript constant name.
///
/// Things AS exposes `open | completed | canceled` as the `status` enum.
/// `Trashed` has no direct equivalent — the proper way to trash a task is
/// `delete_task`, which calls a different script — so we map it to `canceled`
/// as the closest finished state.
fn status_as_applescript(status: TaskStatus) -> &'static str {
    match status {
        TaskStatus::Incomplete => "open",
        TaskStatus::Completed => "completed",
        TaskStatus::Canceled | TaskStatus::Trashed => "canceled",
    }
}

/// Build the `make new to do` script for a [`CreateTaskRequest`].
///
/// Returns the new task's UUID via `return id of newTask`.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #134.
pub(crate) fn create_task_script(req: &CreateTaskRequest) -> String {
    let mut props = vec![format!("name:{}", as_applescript_string(&req.title))];
    if let Some(notes) = &req.notes {
        props.push(format!("notes:{}", as_applescript_string(notes)));
    }
    if let Some(tags) = &req.tags {
        if !tags.is_empty() {
            let joined = tags.join(", ");
            props.push(format!("tag names:{}", as_applescript_string(&joined)));
        }
    }

    let mut body = format!(
        "\t\tset newTask to make new to do with properties {{{}}}\n",
        props.join(", "),
    );

    if let Some(date) = req.start_date {
        body.push_str(&assign_date_var("activationDate", date));
        body.push_str("\t\tset activation date of newTask to activationDate\n");
    }
    if let Some(date) = req.deadline {
        body.push_str(&assign_date_var("dueDate", date));
        body.push_str("\t\tset due date of newTask to dueDate\n");
    }

    // Container precedence matches the sqlx backend: project > area > parent.
    // `set project/area of` avoids error 301 ("Cannot move to-do") that the
    // `move` command produces on a freshly-created task (#158).
    if let Some(uuid) = &req.project_uuid {
        body.push_str(&format!(
            "\t\tset project of newTask to project id \"{uuid}\"\n"
        ));
    } else if let Some(uuid) = &req.area_uuid {
        body.push_str(&format!("\t\tset area of newTask to area id \"{uuid}\"\n"));
    } else if let Some(uuid) = &req.parent_uuid {
        body.push_str(&format!(
            "\t\tset parent task of newTask to to do id \"{uuid}\"\n"
        ));
    }

    if let Some(status) = req.status {
        body.push_str(&format!(
            "\t\tset status of newTask to {}\n",
            status_as_applescript(status),
        ));
    }

    body.push_str("\t\treturn id of newTask\n");
    wrap(&body)
}

/// Build the partial-update script for an [`UpdateTaskRequest`].
///
/// Only emits `set` lines for fields where the corresponding `Option` is
/// `Some` — `None` means "leave unchanged".
#[allow(dead_code)] // Used by AppleScriptBackend, added in #134.
pub(crate) fn update_task_script(req: &UpdateTaskRequest) -> String {
    let mut body = format!("\t\tset t to to do id \"{}\"\n", req.uuid);

    if let Some(title) = &req.title {
        body.push_str(&format!(
            "\t\tset name of t to {}\n",
            as_applescript_string(title),
        ));
    }
    if let Some(notes) = &req.notes {
        body.push_str(&format!(
            "\t\tset notes of t to {}\n",
            as_applescript_string(notes),
        ));
    }
    if let Some(date) = req.start_date {
        body.push_str(&assign_date_var("activationDate", date));
        body.push_str("\t\tset activation date of t to activationDate\n");
    }
    if let Some(date) = req.deadline {
        body.push_str(&assign_date_var("dueDate", date));
        body.push_str("\t\tset due date of t to dueDate\n");
    }
    if let Some(status) = req.status {
        body.push_str(&format!(
            "\t\tset status of t to {}\n",
            status_as_applescript(status),
        ));
    }
    if let Some(uuid) = &req.project_uuid {
        body.push_str(&format!("\t\tmove t to project id \"{uuid}\"\n"));
    } else if let Some(uuid) = &req.area_uuid {
        body.push_str(&format!("\t\tmove t to area id \"{uuid}\"\n"));
    }
    if let Some(tags) = &req.tags {
        let joined = tags.join(", ");
        body.push_str(&format!(
            "\t\tset tag names of t to {}\n",
            as_applescript_string(&joined),
        ));
    }

    wrap(&body)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #134.
pub(crate) fn complete_task_script(id: &ThingsId) -> String {
    wrap(&format!(
        "\t\tset status of to do id \"{id}\" to completed\n"
    ))
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #134.
pub(crate) fn uncomplete_task_script(id: &ThingsId) -> String {
    wrap(&format!("\t\tset status of to do id \"{id}\" to open\n"))
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #134.
pub(crate) fn delete_task_script(id: &ThingsId) -> String {
    // `to do id "<id>"` cannot look up completed (logbook) tasks — they are no
    // longer in the default scope. The `whose id =` clause searches all lists
    // including the logbook, fixing error -1728 on completed tasks (#162).
    wrap(&format!(
        "\t\tset _matches to (every to do whose id = \"{id}\")\n\
         \t\tif (count of _matches) > 0 then delete (item 1 of _matches)\n"
    ))
}

// =====================================================================
// Projects (Phase C — #135)
// =====================================================================

/// Build the `make new project` script for a [`CreateProjectRequest`].
///
/// Returns the new project's UUID via `return id of newProject`.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn create_project_script(req: &CreateProjectRequest) -> String {
    let mut props = vec![format!("name:{}", as_applescript_string(&req.title))];
    if let Some(notes) = &req.notes {
        props.push(format!("notes:{}", as_applescript_string(notes)));
    }
    if let Some(tags) = &req.tags {
        if !tags.is_empty() {
            let joined = tags.join(", ");
            props.push(format!("tag names:{}", as_applescript_string(&joined)));
        }
    }

    let mut body = format!(
        "\t\tset newProject to make new project with properties {{{}}}\n",
        props.join(", "),
    );

    if let Some(date) = req.start_date {
        body.push_str(&assign_date_var("activationDate", date));
        body.push_str("\t\tset activation date of newProject to activationDate\n");
    }
    if let Some(date) = req.deadline {
        body.push_str(&assign_date_var("dueDate", date));
        body.push_str("\t\tset due date of newProject to dueDate\n");
    }

    if let Some(uuid) = &req.area_uuid {
        body.push_str(&format!("\t\tmove newProject to area id \"{uuid}\"\n"));
    }

    body.push_str("\t\treturn id of newProject\n");
    wrap(&body)
}

/// Build the partial-update script for an [`UpdateProjectRequest`].
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn update_project_script(req: &UpdateProjectRequest) -> String {
    let mut body = format!("\t\tset p to project id \"{}\"\n", req.uuid);

    if let Some(title) = &req.title {
        body.push_str(&format!(
            "\t\tset name of p to {}\n",
            as_applescript_string(title),
        ));
    }
    if let Some(notes) = &req.notes {
        body.push_str(&format!(
            "\t\tset notes of p to {}\n",
            as_applescript_string(notes),
        ));
    }
    if let Some(date) = req.start_date {
        body.push_str(&assign_date_var("activationDate", date));
        body.push_str("\t\tset activation date of p to activationDate\n");
    }
    if let Some(date) = req.deadline {
        body.push_str(&assign_date_var("dueDate", date));
        body.push_str("\t\tset due date of p to dueDate\n");
    }
    if let Some(uuid) = &req.area_uuid {
        body.push_str(&format!("\t\tmove p to area id \"{uuid}\"\n"));
    }
    if let Some(tags) = &req.tags {
        let joined = tags.join(", ");
        body.push_str(&format!(
            "\t\tset tag names of p to {}\n",
            as_applescript_string(&joined),
        ));
    }

    wrap(&body)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn complete_project_script(id: &ThingsId) -> String {
    wrap(&format!(
        "\t\tset status of project id \"{id}\" to completed\n"
    ))
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn delete_project_script(id: &ThingsId) -> String {
    wrap(&format!("\t\tdelete project id \"{id}\"\n"))
}

/// Build a cascading complete-project script: completes every child task in
/// `child_ids`, then completes the project. Single osascript invocation.
/// Fail-fast — if any sub-statement raises, the project status is left untouched.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn cascade_complete_project_script(
    project_id: &ThingsId,
    child_ids: &[ThingsId],
) -> String {
    let mut body = String::new();
    for child in child_ids {
        body.push_str(&format!(
            "\t\tset status of to do id \"{child}\" to completed\n"
        ));
    }
    body.push_str(&format!(
        "\t\tset status of project id \"{project_id}\" to completed\n"
    ));
    wrap(&body)
}

/// Build a cascading delete-project script: deletes every child task in
/// `child_ids`, then deletes the project. Single osascript invocation.
/// Fail-fast — if any sub-statement raises, the project is left untouched.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn cascade_delete_project_script(
    project_id: &ThingsId,
    child_ids: &[ThingsId],
) -> String {
    let mut body = String::new();
    for child in child_ids {
        body.push_str(&format!("\t\tdelete to do id \"{child}\"\n"));
    }
    body.push_str(&format!("\t\tdelete project id \"{project_id}\"\n"));
    wrap(&body)
}

/// Build an orphan-then-complete-project script: detaches every child task
/// (`set project to missing value`), then completes the project.
/// Fail-fast — if any sub-statement raises, the project is left untouched.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn orphan_complete_project_script(
    project_id: &ThingsId,
    child_ids: &[ThingsId],
) -> String {
    let mut body = String::new();
    for child in child_ids {
        body.push_str(&format!(
            "\t\tset project of to do id \"{child}\" to missing value\n"
        ));
    }
    body.push_str(&format!(
        "\t\tset status of project id \"{project_id}\" to completed\n"
    ));
    wrap(&body)
}

/// Build an orphan-then-delete-project script: detaches every child task,
/// then deletes the project.
/// Fail-fast — if any sub-statement raises, the project is left untouched.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn orphan_delete_project_script(
    project_id: &ThingsId,
    child_ids: &[ThingsId],
) -> String {
    let mut body = String::new();
    for child in child_ids {
        body.push_str(&format!(
            "\t\tset project of to do id \"{child}\" to missing value\n"
        ));
    }
    body.push_str(&format!("\t\tdelete project id \"{project_id}\"\n"));
    wrap(&body)
}

// =====================================================================
// Areas (Phase C — #135)
// =====================================================================

/// Build the `make new area` script for a [`CreateAreaRequest`].
///
/// Returns the new area's UUID via `return id of newArea`.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn create_area_script(req: &CreateAreaRequest) -> String {
    let body = format!(
        "\t\tset newArea to make new area with properties {{name:{}}}\n\
         \t\treturn id of newArea\n",
        as_applescript_string(&req.title),
    );
    wrap(&body)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn update_area_script(req: &UpdateAreaRequest) -> String {
    wrap(&format!(
        "\t\tset name of area id \"{}\" to {}\n",
        req.uuid,
        as_applescript_string(&req.title),
    ))
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn delete_area_script(id: &ThingsId) -> String {
    wrap(&format!("\t\tdelete area id \"{id}\"\n"))
}

// =====================================================================
// Bulk operations (Phase C — #135)
// =====================================================================

/// Wrap a sequence of per-item snippets in a try/on-error harness.
///
/// Each snippet runs inside its own `try ... on error ... end try` block. On
/// success, an `okCount` counter increments. On failure, the index and
/// AppleScript error message are appended to an `errorList`. The script
/// returns:
///
/// - `"OK <count>"` if no errors
/// - `"OK <count>\nitem <idx>: <msg>\nitem <idx>: <msg>\n..."` otherwise
///
/// Parsed by [`super::parse::parse_bulk_result`].
fn bulk_wrap(per_item: &[String]) -> String {
    let mut body = String::from("\t\tset okCount to 0\n\t\tset errorList to {}\n");
    for (idx, snippet) in per_item.iter().enumerate() {
        body.push_str("\t\ttry\n");
        body.push_str(snippet);
        body.push_str("\t\t\tset okCount to okCount + 1\n");
        body.push_str("\t\ton error errMsg\n");
        body.push_str(&format!(
            "\t\t\tset end of errorList to \"item {idx}: \" & errMsg\n"
        ));
        body.push_str("\t\tend try\n");
    }
    body.push_str("\t\tif (count of errorList) is 0 then\n");
    body.push_str("\t\t\treturn \"OK \" & okCount\n");
    body.push_str("\t\telse\n");
    body.push_str("\t\t\tset oldDelims to AppleScript's text item delimiters\n");
    body.push_str("\t\t\tset AppleScript's text item delimiters to linefeed\n");
    body.push_str("\t\t\tset output to \"OK \" & okCount & linefeed & (errorList as string)\n");
    body.push_str("\t\t\tset AppleScript's text item delimiters to oldDelims\n");
    body.push_str("\t\t\treturn output\n");
    body.push_str("\t\tend if\n");
    wrap(&body)
}

/// Render the property-list + post-statements for a single `make new to do`
/// inside the atomic bulk-create script. Indented one extra level (`\t\t\t`)
/// to sit inside the single outer `try` block.
///
/// Caller contract: the caller must declare `set createdTasks to {}` before
/// the first snippet runs; each snippet appends `newTask` to that list so the
/// outer `on error` handler can delete them all on rollback.
fn create_task_snippet(req: &CreateTaskRequest) -> String {
    let mut props = vec![format!("name:{}", as_applescript_string(&req.title))];
    if let Some(notes) = &req.notes {
        props.push(format!("notes:{}", as_applescript_string(notes)));
    }
    if let Some(tags) = &req.tags {
        if !tags.is_empty() {
            let joined = tags.join(", ");
            props.push(format!("tag names:{}", as_applescript_string(&joined)));
        }
    }

    let mut snippet = format!(
        "\t\t\tset newTask to make new to do with properties {{{}}}\n\
         \t\t\tset end of createdTasks to newTask\n",
        props.join(", "),
    );

    if let Some(date) = req.start_date {
        snippet.push_str(&assign_date_var_indented("activationDate", date, 3));
        snippet.push_str("\t\t\tset activation date of newTask to activationDate\n");
    }
    if let Some(date) = req.deadline {
        snippet.push_str(&assign_date_var_indented("dueDate", date, 3));
        snippet.push_str("\t\t\tset due date of newTask to dueDate\n");
    }

    if let Some(uuid) = &req.project_uuid {
        snippet.push_str(&format!(
            "\t\t\tset project of newTask to project id \"{uuid}\"\n"
        ));
    } else if let Some(uuid) = &req.area_uuid {
        snippet.push_str(&format!(
            "\t\t\tset area of newTask to area id \"{uuid}\"\n"
        ));
    } else if let Some(uuid) = &req.parent_uuid {
        snippet.push_str(&format!("\t\t\tmove newTask to to do id \"{uuid}\"\n"));
    }

    if let Some(status) = req.status {
        snippet.push_str(&format!(
            "\t\t\tset status of newTask to {}\n",
            status_as_applescript(status),
        ));
    }
    snippet
}

/// Indented variant of [`assign_date_var`] for use inside bulk try-blocks.
fn assign_date_var_indented(var: &str, date: NaiveDate, level: usize) -> String {
    let tabs = "\t".repeat(level);
    format!(
        "{tabs}set {var} to current date\n\
         {tabs}set day of {var} to 1\n\
         {tabs}set year of {var} to {year}\n\
         {tabs}set month of {var} to {month}\n\
         {tabs}set day of {var} to {day}\n\
         {tabs}set time of {var} to 0\n",
        year = date.year(),
        month = date.month(),
        day = date.day(),
    )
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn bulk_create_tasks_script(req: &BulkCreateTasksRequest) -> String {
    // All tasks are created inside a single try block. If any step fails the
    // on-error handler deletes every task already added to `createdTasks` and
    // returns a "ROLLBACK: <msg>" sentinel so the caller knows nothing was left
    // behind. This prevents orphaned inbox tasks when e.g. a project_uuid is
    // invalid. Parsed by [`super::parse::parse_atomic_bulk_create_result`].
    let mut body = String::from("\t\tset createdTasks to {}\n\t\ttry\n");
    for snippet in req.tasks.iter().map(create_task_snippet) {
        body.push_str(&snippet);
    }
    body.push_str("\t\t\treturn \"OK \" & (count of createdTasks)\n");
    body.push_str("\t\ton error errMsg\n");
    body.push_str("\t\t\trepeat with t in createdTasks\n");
    body.push_str("\t\t\t\ttry\n");
    body.push_str("\t\t\t\t\tdelete t\n");
    body.push_str("\t\t\t\tend try\n");
    body.push_str("\t\t\tend repeat\n");
    body.push_str("\t\t\treturn \"ROLLBACK: \" & errMsg\n");
    body.push_str("\t\tend try\n");
    wrap(&body)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn bulk_delete_script(req: &BulkDeleteRequest) -> String {
    // Use `whose id =` so completed (logbook) items are also reachable (#162).
    let snippets: Vec<String> = req
        .task_uuids
        .iter()
        .map(|id| {
            format!(
                "\t\t\tset _m to (every to do whose id = \"{id}\")\n\
                 \t\t\tif (count of _m) > 0 then delete (item 1 of _m)\n"
            )
        })
        .collect();
    bulk_wrap(&snippets)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn bulk_complete_script(req: &BulkCompleteRequest) -> String {
    let snippets: Vec<String> = req
        .task_uuids
        .iter()
        .map(|id| format!("\t\t\tset status of to do id \"{id}\" to completed\n"))
        .collect();
    bulk_wrap(&snippets)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn bulk_move_script(req: &BulkMoveRequest) -> String {
    let dest = if let Some(uuid) = &req.project_uuid {
        format!("project id \"{uuid}\"")
    } else if let Some(uuid) = &req.area_uuid {
        format!("area id \"{uuid}\"")
    } else {
        unreachable!(
            "bulk_move_script called without project_uuid or area_uuid; \
             bulk_move() must validate before constructing the script"
        );
    };
    let snippets: Vec<String> = req
        .task_uuids
        .iter()
        .map(|id| format!("\t\t\tmove to do id \"{id}\" to {dest}\n"))
        .collect();
    bulk_wrap(&snippets)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #135.
pub(crate) fn bulk_update_dates_script(req: &BulkUpdateDatesRequest) -> String {
    // Build the per-item snippet once: it depends only on the request, not the id.
    // Date variables are assigned once per try-block; per-item set statements reference them.
    let snippets: Vec<String> = req
        .task_uuids
        .iter()
        .map(|id| {
            let mut snippet = format!("\t\t\tset t to to do id \"{id}\"\n");
            if let Some(date) = req.start_date {
                snippet.push_str(&assign_date_var_indented("activationDate", date, 3));
                snippet.push_str("\t\t\tset activation date of t to activationDate\n");
            } else if req.clear_start_date {
                snippet.push_str("\t\t\tset activation date of t to missing value\n");
            }
            if let Some(date) = req.deadline {
                snippet.push_str(&assign_date_var_indented("dueDate", date, 3));
                snippet.push_str("\t\t\tset due date of t to dueDate\n");
            } else if req.clear_deadline {
                snippet.push_str("\t\t\tset due date of t to missing value\n");
            }
            snippet
        })
        .collect();
    bulk_wrap(&snippets)
}

// =====================================================================
// Tags (Phase D — #136)
// =====================================================================

/// Build the `make new tag` script for a [`CreateTagRequest`].
///
/// Returns the new tag's UUID via `return id of newTag`.
///
/// **Note:** Things AppleScript does not expose `shortcut` or `parent`
/// properties on `tag`, so [`CreateTagRequest::shortcut`] and
/// [`CreateTagRequest::parent_uuid`] are silently dropped here. The caller
/// is responsible for `tracing::debug!`-logging that drop. This is a known
/// divergence from `SqlxBackend` — see Phase D PR notes (#136).
#[allow(dead_code)] // Used by AppleScriptBackend, added in #136.
pub(crate) fn create_tag_script(req: &CreateTagRequest) -> String {
    let body = format!(
        "\t\tset newTag to make new tag with properties {{name:{}}}\n\
         \t\treturn id of newTag\n",
        as_applescript_string(&req.title),
    );
    wrap(&body)
}

/// Build the partial-update script for an [`UpdateTagRequest`].
///
/// Same `shortcut` / `parent_uuid` caveat as [`create_tag_script`] — those
/// fields are silently ignored.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #136.
pub(crate) fn update_tag_script(req: &UpdateTagRequest) -> String {
    let mut body = format!("\t\tset t to tag id \"{}\"\n", req.uuid);
    if let Some(title) = &req.title {
        body.push_str(&format!(
            "\t\tset name of t to {}\n",
            as_applescript_string(title),
        ));
    }
    wrap(&body)
}

#[allow(dead_code)] // Used by AppleScriptBackend, added in #136.
pub(crate) fn delete_tag_script(id: &ThingsId) -> String {
    wrap(&format!("\t\tdelete tag id \"{id}\"\n"))
}

/// Set a task's `tag names` property to the provided comma-joined string.
///
/// Things AS treats `tag names` as a single text value: a comma-separated
/// list that Things parses internally. Caller is responsible for joining
/// titles with `", "` and for any deduplication.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #136.
pub(crate) fn set_task_tag_names_script(task_id: &ThingsId, joined: &str) -> String {
    wrap(&format!(
        "\t\tset tag names of to do id \"{task_id}\" to {}\n",
        as_applescript_string(joined),
    ))
}

/// Return the `tag names` string for a task. Things 3 stores tag names as a
/// comma-separated text property; an untagged task returns an empty string.
/// Used by `read_task_tag_titles` to avoid parsing the proprietary binary
/// blob that Things 3 writes to `cachedTags` after an AppleScript mutation.
pub(crate) fn get_task_tag_names_script(task_id: &ThingsId) -> String {
    wrap(&format!("\t\treturn tag names of to do id \"{task_id}\"\n"))
}

/// Bulk variant of [`set_task_tag_names_script`] — one osascript invocation
/// rewrites tag names for many tasks. Each item runs in its own try block
/// via [`bulk_wrap`]. Used by `merge_tags` and `delete_tag(remove_from_tasks=true)`.
#[allow(dead_code)] // Used by AppleScriptBackend, added in #136.
pub(crate) fn bulk_set_task_tag_names_script(items: &[(ThingsId, String)]) -> String {
    let snippets: Vec<String> = items
        .iter()
        .map(|(task_id, joined)| {
            format!(
                "\t\t\tset tag names of to do id \"{task_id}\" to {}\n",
                as_applescript_string(joined),
            )
        })
        .collect();
    bulk_wrap(&snippets)
}

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

    fn sample_uuid() -> ThingsId {
        ThingsId::from_trusted("9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e".to_string())
    }

    fn project_uuid() -> ThingsId {
        ThingsId::from_trusted("11111111-2222-3333-4444-555555555555".to_string())
    }

    fn date(y: i32, m: u32, d: u32) -> NaiveDate {
        NaiveDate::from_ymd_opt(y, m, d).unwrap()
    }

    #[test]
    fn create_task_minimal_title_only() {
        let req = CreateTaskRequest {
            title: "Buy milk".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        };
        let script = create_task_script(&req);
        assert!(script.starts_with("tell application \"Things3\""));
        assert!(script.contains("with timeout of 600 seconds"));
        assert!(script.contains("make new to do with properties {name:\"Buy milk\"}"));
        assert!(script.contains("return id of newTask"));
        assert!(script.ends_with("end tell\n"));
        // No date / move / status lines.
        assert!(!script.contains("activation date"));
        assert!(!script.contains("due date"));
        assert!(!script.contains("move newTask"));
        assert!(!script.contains("set status"));
    }

    #[test]
    fn create_task_escapes_title_and_notes() {
        let req = CreateTaskRequest {
            title: "Buy \"organic\" milk".into(),
            task_type: None,
            notes: Some("Has\nnewline and \\ backslash".into()),
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        };
        let script = create_task_script(&req);
        assert!(script.contains("name:\"Buy \\\"organic\\\" milk\""));
        assert!(script.contains("notes:\"Has\\nnewline and \\\\ backslash\""));
    }

    #[test]
    fn create_task_with_tags_joins_with_comma() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: Some(vec!["work".into(), "urgent".into()]),
            status: None,
        };
        let script = create_task_script(&req);
        assert!(script.contains("tag names:\"work, urgent\""));
    }

    #[test]
    fn create_task_with_empty_tags_omits_property() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: Some(vec![]),
            status: None,
        };
        let script = create_task_script(&req);
        assert!(!script.contains("tag names"));
    }

    #[test]
    fn create_task_with_dates_sets_components_locale_independently() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: Some(date(2026, 4, 15)),
            deadline: Some(date(2026, 5, 1)),
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        };
        let script = create_task_script(&req);
        // activation date setup
        assert!(script.contains("set activationDate to current date"));
        assert!(script.contains("set day of activationDate to 1"));
        assert!(script.contains("set year of activationDate to 2026"));
        assert!(script.contains("set month of activationDate to 4"));
        assert!(script.contains("set day of activationDate to 15"));
        assert!(script.contains("set activation date of newTask to activationDate"));
        // due date setup
        assert!(script.contains("set dueDate to current date"));
        assert!(script.contains("set month of dueDate to 5"));
        assert!(script.contains("set day of dueDate to 1"));
        assert!(script.contains("set due date of newTask to dueDate"));
    }

    #[test]
    fn create_task_with_project_emits_set_project() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: Some(project_uuid()),
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        };
        let script = create_task_script(&req);
        assert!(script.contains(&format!(
            "set project of newTask to project id \"{}\"",
            project_uuid()
        )));
        assert!(!script.contains("move newTask"));
    }

    #[test]
    fn create_task_project_takes_precedence_over_area() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: Some(project_uuid()),
            area_uuid: Some(sample_uuid()),
            parent_uuid: None,
            tags: None,
            status: None,
        };
        let script = create_task_script(&req);
        assert!(script.contains("set project of newTask to project id"));
        assert!(!script.contains("set area of newTask to area id"));
        assert!(!script.contains("move newTask"));
    }

    #[test]
    fn create_task_with_status_emits_set_status() {
        let req = CreateTaskRequest {
            title: "x".into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: Some(TaskStatus::Completed),
        };
        let script = create_task_script(&req);
        assert!(script.contains("set status of newTask to completed"));
    }

    #[test]
    fn update_task_no_fields_only_resolves_target() {
        let req = UpdateTaskRequest {
            uuid: sample_uuid(),
            title: None,
            notes: None,
            start_date: None,
            deadline: None,
            status: None,
            project_uuid: None,
            area_uuid: None,
            tags: None,
        };
        let script = update_task_script(&req);
        assert!(script.contains(&format!("set t to to do id \"{}\"", sample_uuid())));
        assert!(!script.contains("set name"));
        assert!(!script.contains("set notes"));
        assert!(!script.contains("set status"));
        assert!(!script.contains("move t"));
        assert!(!script.contains("set tag names"));
    }

    #[test]
    fn update_task_emits_only_specified_fields() {
        let req = UpdateTaskRequest {
            uuid: sample_uuid(),
            title: Some("renamed".into()),
            notes: None,
            start_date: None,
            deadline: None,
            status: Some(TaskStatus::Canceled),
            project_uuid: None,
            area_uuid: None,
            tags: Some(vec!["a".into(), "b".into()]),
        };
        let script = update_task_script(&req);
        assert!(script.contains("set name of t to \"renamed\""));
        assert!(script.contains("set status of t to canceled"));
        assert!(script.contains("set tag names of t to \"a, b\""));
        assert!(!script.contains("set notes"));
        assert!(!script.contains("activation date"));
        assert!(!script.contains("due date"));
    }

    #[test]
    fn update_task_trashed_status_maps_to_canceled() {
        let req = UpdateTaskRequest {
            uuid: sample_uuid(),
            title: None,
            notes: None,
            start_date: None,
            deadline: None,
            status: Some(TaskStatus::Trashed),
            project_uuid: None,
            area_uuid: None,
            tags: None,
        };
        let script = update_task_script(&req);
        assert!(script.contains("set status of t to canceled"));
    }

    #[test]
    fn complete_task_script_shape() {
        let script = complete_task_script(&sample_uuid());
        assert!(script.contains(&format!(
            "set status of to do id \"{}\" to completed",
            sample_uuid()
        )));
    }

    #[test]
    fn uncomplete_task_script_shape() {
        let script = uncomplete_task_script(&sample_uuid());
        assert!(script.contains(&format!(
            "set status of to do id \"{}\" to open",
            sample_uuid()
        )));
    }

    #[test]
    fn delete_task_script_shape() {
        let id = sample_uuid();
        let script = delete_task_script(&id);
        // Uses `whose id =` so logbook (completed) tasks are reachable (#162).
        assert!(script.contains(&format!("every to do whose id = \"{}\"", id)));
        assert!(script.contains("delete (item 1 of _matches)"));
        assert!(!script.contains(&format!("delete to do id \"{}\"", id)));
    }

    #[test]
    fn all_scripts_wrapped_in_timeout() {
        let id = sample_uuid();
        for script in [
            complete_task_script(&id),
            uncomplete_task_script(&id),
            delete_task_script(&id),
        ] {
            assert!(
                script.contains("with timeout of 600 seconds"),
                "script was: {script}"
            );
            assert!(script.contains("end timeout"), "script was: {script}");
            assert!(script.starts_with("tell application \"Things3\""));
            assert!(script.ends_with("end tell\n"));
        }
    }

    #[test]
    fn assign_date_var_sets_day_to_1_first_to_avoid_overflow() {
        let snippet = assign_date_var("d", date(2026, 4, 15));
        let day1_pos = snippet.find("set day of d to 1").unwrap();
        let month_pos = snippet.find("set month of d to 4").unwrap();
        let final_day_pos = snippet.find("set day of d to 15").unwrap();
        assert!(day1_pos < month_pos, "day=1 must precede month assignment");
        assert!(
            month_pos < final_day_pos,
            "final day assignment must come last"
        );
    }

    // -----------------------------------------------------------------
    // Phase C — Projects
    // -----------------------------------------------------------------

    #[test]
    fn create_project_minimal() {
        let req = CreateProjectRequest {
            title: "Launch".into(),
            notes: None,
            area_uuid: None,
            start_date: None,
            deadline: None,
            tags: None,
        };
        let script = create_project_script(&req);
        assert!(script.contains("make new project with properties {name:\"Launch\"}"));
        assert!(script.contains("return id of newProject"));
        assert!(!script.contains("move newProject"));
    }

    #[test]
    fn create_project_with_area_emits_move() {
        let req = CreateProjectRequest {
            title: "x".into(),
            notes: Some("notes\nwith newline".into()),
            area_uuid: Some(project_uuid()),
            start_date: Some(date(2026, 7, 4)),
            deadline: None,
            tags: Some(vec!["ops".into(), "urgent".into()]),
        };
        let script = create_project_script(&req);
        assert!(script.contains("notes:\"notes\\nwith newline\""));
        assert!(script.contains("tag names:\"ops, urgent\""));
        assert!(script.contains(&format!(
            "move newProject to area id \"{}\"",
            project_uuid()
        )));
        assert!(script.contains("set activation date of newProject to activationDate"));
    }

    #[test]
    fn update_project_emits_only_specified_fields() {
        let req = UpdateProjectRequest {
            uuid: sample_uuid(),
            title: Some("renamed".into()),
            notes: None,
            area_uuid: None,
            start_date: None,
            deadline: Some(date(2026, 12, 31)),
            tags: None,
        };
        let script = update_project_script(&req);
        assert!(script.contains(&format!("set p to project id \"{}\"", sample_uuid())));
        assert!(script.contains("set name of p to \"renamed\""));
        assert!(script.contains("set due date of p to dueDate"));
        assert!(!script.contains("set notes"));
        assert!(!script.contains("set tag names"));
    }

    #[test]
    fn complete_project_script_shape() {
        let script = complete_project_script(&sample_uuid());
        assert!(script.contains(&format!(
            "set status of project id \"{}\" to completed",
            sample_uuid()
        )));
    }

    #[test]
    fn delete_project_script_shape() {
        let script = delete_project_script(&sample_uuid());
        assert!(script.contains(&format!("delete project id \"{}\"", sample_uuid())));
    }

    #[test]
    fn cascade_complete_project_includes_each_child_and_parent() {
        let project = sample_uuid();
        let children = vec![project_uuid(), ThingsId::from_trusted("abc-123".into())];
        let script = cascade_complete_project_script(&project, &children);
        for child in &children {
            assert!(script.contains(&format!("set status of to do id \"{child}\" to completed")));
        }
        assert!(script.contains(&format!(
            "set status of project id \"{project}\" to completed"
        )));
    }

    #[test]
    fn cascade_delete_project_includes_each_child_and_parent() {
        let project = sample_uuid();
        let children = vec![project_uuid()];
        let script = cascade_delete_project_script(&project, &children);
        assert!(script.contains(&format!("delete to do id \"{}\"", project_uuid())));
        assert!(script.contains(&format!("delete project id \"{project}\"")));
        // Order matters: children deleted before parent.
        let child_pos = script.find("delete to do id").unwrap();
        let parent_pos = script.find("delete project id").unwrap();
        assert!(child_pos < parent_pos);
    }

    #[test]
    fn orphan_complete_project_uses_missing_value_for_children() {
        let project = sample_uuid();
        let children = vec![project_uuid()];
        let script = orphan_complete_project_script(&project, &children);
        assert!(script.contains(&format!(
            "set project of to do id \"{}\" to missing value",
            project_uuid()
        )));
        assert!(script.contains(&format!(
            "set status of project id \"{project}\" to completed"
        )));
    }

    #[test]
    fn orphan_delete_project_uses_missing_value_for_children() {
        let project = sample_uuid();
        let children = vec![project_uuid()];
        let script = orphan_delete_project_script(&project, &children);
        assert!(script.contains(&format!(
            "set project of to do id \"{}\" to missing value",
            project_uuid()
        )));
        assert!(script.contains(&format!("delete project id \"{project}\"")));
    }

    // -----------------------------------------------------------------
    // Phase C — Areas
    // -----------------------------------------------------------------

    #[test]
    fn create_area_script_returns_id() {
        let script = create_area_script(&CreateAreaRequest {
            title: "Personal \"life\"".into(),
        });
        assert!(script.contains("make new area with properties {name:\"Personal \\\"life\\\"\"}"));
        assert!(script.contains("return id of newArea"));
    }

    #[test]
    fn update_area_renames() {
        let script = update_area_script(&UpdateAreaRequest {
            uuid: sample_uuid(),
            title: "New name".into(),
        });
        assert!(script.contains(&format!(
            "set name of area id \"{}\" to \"New name\"",
            sample_uuid()
        )));
    }

    #[test]
    fn delete_area_script_shape() {
        let script = delete_area_script(&sample_uuid());
        assert!(script.contains(&format!("delete area id \"{}\"", sample_uuid())));
    }

    // -----------------------------------------------------------------
    // Phase C — Bulk operations
    // -----------------------------------------------------------------

    fn task(title: &str) -> CreateTaskRequest {
        CreateTaskRequest {
            title: title.into(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        }
    }

    #[test]
    fn bulk_create_tasks_is_atomic_with_rollback() {
        let req = BulkCreateTasksRequest {
            tasks: vec![task("a"), task("b")],
        };
        let script = bulk_create_tasks_script(&req);
        // Single outer try/on-error — NOT per-item try blocks.
        // Use "\n\t\ttry\n" to anchor at line start (prevents matching inside
        // "\t\t\t\ttry\n" inside the rollback repeat).
        assert_eq!(script.matches("\n\t\ttry\n").count(), 1);
        assert_eq!(script.matches("on error errMsg").count(), 1);
        // createdTasks list is initialised and each task is appended.
        assert!(script.contains("set createdTasks to {}"));
        assert_eq!(
            script.matches("set end of createdTasks to newTask").count(),
            2
        );
        // On success: return "OK <count>".
        assert!(script.contains("return \"OK \" & (count of createdTasks)"));
        // On error: rollback loop, then return ROLLBACK sentinel.
        assert!(script.contains("repeat with t in createdTasks"));
        assert!(script.contains("delete t"));
        assert!(script.contains("return \"ROLLBACK: \" & errMsg"));
        // Both task names present.
        assert!(script.contains("name:\"a\""));
        assert!(script.contains("name:\"b\""));
        // Container assignment uses set-property, not move (#158).
        assert!(!script.contains("move newTask"));
    }

    #[test]
    fn bulk_delete_one_per_item() {
        let req = BulkDeleteRequest {
            task_uuids: vec![sample_uuid(), project_uuid()],
        };
        let script = bulk_delete_script(&req);
        // Uses `whose id =` so logbook items are reachable (#162).
        assert!(script.contains(&format!("every to do whose id = \"{}\"", sample_uuid())));
        assert!(script.contains(&format!("every to do whose id = \"{}\"", project_uuid())));
        assert!(!script.contains(&format!("delete to do id \"{}\"", sample_uuid())));
        assert_eq!(script.matches("\t\ttry\n").count(), 2);
        assert_eq!(script.matches("on error errMsg").count(), 2);
    }

    #[test]
    fn bulk_complete_one_per_item() {
        let req = BulkCompleteRequest {
            task_uuids: vec![sample_uuid()],
        };
        let script = bulk_complete_script(&req);
        assert!(script.contains(&format!(
            "set status of to do id \"{}\" to completed",
            sample_uuid()
        )));
    }

    #[test]
    fn bulk_move_emits_project_destination() {
        let req = BulkMoveRequest {
            task_uuids: vec![sample_uuid()],
            project_uuid: Some(project_uuid()),
            area_uuid: None,
        };
        let script = bulk_move_script(&req);
        assert!(script.contains(&format!(
            "move to do id \"{}\" to project id \"{}\"",
            sample_uuid(),
            project_uuid()
        )));
    }

    #[test]
    fn bulk_move_prefers_project_over_area_when_both_set() {
        let req = BulkMoveRequest {
            task_uuids: vec![sample_uuid()],
            project_uuid: Some(project_uuid()),
            area_uuid: Some(sample_uuid()),
        };
        let script = bulk_move_script(&req);
        assert!(script.contains("to project id"));
        assert!(!script.contains("to area id"));
    }

    #[test]
    fn bulk_move_emits_area_destination_when_project_unset() {
        let req = BulkMoveRequest {
            task_uuids: vec![sample_uuid()],
            project_uuid: None,
            area_uuid: Some(project_uuid()),
        };
        let script = bulk_move_script(&req);
        assert!(script.contains(&format!(
            "move to do id \"{}\" to area id \"{}\"",
            sample_uuid(),
            project_uuid()
        )));
    }

    #[test]
    #[should_panic(expected = "bulk_move_script called without project_uuid or area_uuid")]
    fn bulk_move_without_destination_panics() {
        let req = BulkMoveRequest {
            task_uuids: vec![sample_uuid()],
            project_uuid: None,
            area_uuid: None,
        };
        let _ = bulk_move_script(&req);
    }

    #[test]
    fn bulk_update_dates_with_clears() {
        let req = BulkUpdateDatesRequest {
            task_uuids: vec![sample_uuid()],
            start_date: None,
            deadline: None,
            clear_start_date: true,
            clear_deadline: true,
        };
        let script = bulk_update_dates_script(&req);
        assert!(script.contains("set activation date of t to missing value"));
        assert!(script.contains("set due date of t to missing value"));
    }

    #[test]
    fn bulk_update_dates_with_values() {
        let req = BulkUpdateDatesRequest {
            task_uuids: vec![sample_uuid()],
            start_date: Some(date(2026, 6, 1)),
            deadline: Some(date(2026, 7, 1)),
            clear_start_date: false,
            clear_deadline: false,
        };
        let script = bulk_update_dates_script(&req);
        assert!(script.contains("set activation date of t to activationDate"));
        assert!(script.contains("set due date of t to dueDate"));
    }

    // -----------------------------------------------------------------
    // Phase D — Tags
    // -----------------------------------------------------------------

    #[test]
    fn create_tag_emits_make_new_with_name_only() {
        let req = CreateTagRequest {
            title: "Work".into(),
            shortcut: Some("w".into()),
            parent_uuid: Some(sample_uuid()),
        };
        let script = create_tag_script(&req);
        assert!(script.contains("make new tag with properties {name:\"Work\"}"));
        assert!(script.contains("return id of newTag"));
        // shortcut and parent are intentionally dropped — Things AS does not
        // expose them. The Rust backend logs the drop at debug level.
        assert!(!script.contains("shortcut"));
        assert!(!script.contains("parent"));
    }

    #[test]
    fn create_tag_escapes_title() {
        let req = CreateTagRequest {
            title: "Has \"quotes\" and\nnewline".into(),
            shortcut: None,
            parent_uuid: None,
        };
        let script = create_tag_script(&req);
        assert!(script.contains("name:\"Has \\\"quotes\\\" and\\nnewline\""));
    }

    #[test]
    fn update_tag_no_fields_only_resolves_target() {
        let req = UpdateTagRequest {
            uuid: sample_uuid(),
            title: None,
            shortcut: Some("w".into()),
            parent_uuid: Some(project_uuid()),
        };
        let script = update_tag_script(&req);
        assert!(script.contains(&format!("set t to tag id \"{}\"", sample_uuid())));
        assert!(!script.contains("set name"));
        // shortcut/parent silently dropped
        assert!(!script.contains("shortcut"));
        assert!(!script.contains("parent"));
    }

    #[test]
    fn update_tag_renames_when_title_set() {
        let req = UpdateTagRequest {
            uuid: sample_uuid(),
            title: Some("Renamed".into()),
            shortcut: None,
            parent_uuid: None,
        };
        let script = update_tag_script(&req);
        assert!(script.contains("set name of t to \"Renamed\""));
    }

    #[test]
    fn delete_tag_script_shape() {
        let script = delete_tag_script(&sample_uuid());
        assert!(script.contains(&format!("delete tag id \"{}\"", sample_uuid())));
    }

    #[test]
    fn set_task_tag_names_emits_set_with_joined_string() {
        let script = set_task_tag_names_script(&sample_uuid(), "work, urgent");
        assert!(script.contains(&format!(
            "set tag names of to do id \"{}\" to \"work, urgent\"",
            sample_uuid()
        )));
    }

    #[test]
    fn set_task_tag_names_escapes_joined_string() {
        let script = set_task_tag_names_script(&sample_uuid(), "has \"quote\"");
        assert!(script.contains("\"has \\\"quote\\\"\""));
    }

    #[test]
    fn bulk_set_task_tag_names_wraps_each_in_try_block() {
        let items = vec![
            (sample_uuid(), "a, b".to_string()),
            (project_uuid(), "c".to_string()),
        ];
        let script = bulk_set_task_tag_names_script(&items);
        // Each item gets its own try block.
        assert_eq!(script.matches("\t\ttry\n").count(), 2);
        assert_eq!(script.matches("on error errMsg").count(), 2);
        assert_eq!(script.matches("end try").count(), 2);
        assert!(script.contains(&format!(
            "set tag names of to do id \"{}\" to \"a, b\"",
            sample_uuid()
        )));
        assert!(script.contains(&format!(
            "set tag names of to do id \"{}\" to \"c\"",
            project_uuid()
        )));
        // Per-item error tagging.
        assert!(script.contains("\"item 0: \" & errMsg"));
        assert!(script.contains("\"item 1: \" & errMsg"));
    }

    #[test]
    fn bulk_set_task_tag_names_empty_items_still_returns_ok() {
        let script = bulk_set_task_tag_names_script(&[]);
        assert!(script.contains("set okCount to 0"));
        assert!(script.contains("return \"OK \" & okCount"));
        assert_eq!(script.matches("\t\ttry\n").count(), 0);
    }
}