gdelt 0.1.0

CLI for GDELT Project - optimized for agentic usage with local data caching
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
1426
1427
1428
1429
1430
//! CLI argument parsing and command definitions.
//!
//! This module defines the complete command hierarchy for the GDELT CLI,
//! optimized for both human and AI agent usage.

use clap::{Args, Parser, Subcommand, ValueEnum};
use std::path::PathBuf;

/// GDELT CLI - Query and analyze global event data
///
/// A comprehensive CLI for the GDELT Project, optimized for agentic usage.
/// Supports local data caching with DuckDB, real-time API access, and
/// built-in analytics.
#[derive(Parser, Debug)]
#[command(name = "gdelt")]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,

    #[command(flatten)]
    pub global: GlobalArgs,
}

/// Global arguments available on all commands
#[derive(Args, Debug, Clone)]
pub struct GlobalArgs {
    /// Output format
    #[arg(short, long, global = true, value_enum, default_value = "auto")]
    pub output: OutputFormat,

    /// Shorthand for --output json
    #[arg(long, global = true, conflicts_with = "output")]
    pub json: bool,

    /// Shorthand for --output jsonl (streaming)
    #[arg(long, global = true, conflicts_with = "output")]
    pub jsonl: bool,

    /// Shorthand for --output csv
    #[arg(long, global = true, conflicts_with = "output")]
    pub csv: bool,

    /// Shorthand for --output table
    #[arg(long, global = true, conflicts_with = "output")]
    pub table: bool,

    /// Shorthand for --output markdown
    #[arg(long, global = true, conflicts_with = "output")]
    pub markdown: bool,

    /// Pretty-print output (default for TTY)
    #[arg(long, global = true)]
    pub pretty: bool,

    /// Compact output (no whitespace)
    #[arg(long, global = true, conflicts_with = "pretty")]
    pub compact: bool,

    /// Suppress non-essential output
    #[arg(short, long, global = true)]
    pub quiet: bool,

    /// Increase verbosity (-v, -vv, -vvv)
    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Show what would be done without executing
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Auto-confirm all prompts
    #[arg(short, long, global = true)]
    pub yes: bool,

    /// Bypass cache for this request
    #[arg(long, global = true)]
    pub no_cache: bool,

    /// Only return cached results (fail if miss)
    #[arg(long, global = true, conflicts_with = "no_cache")]
    pub cache_only: bool,

    /// Request timeout in seconds
    #[arg(long, global = true, default_value = "30")]
    pub timeout: u64,

    /// Number of retry attempts
    #[arg(long, global = true, default_value = "3")]
    pub retries: u32,

    /// Wait and retry when rate limited (shows countdown)
    #[arg(long, global = true)]
    pub wait_on_rate_limit: bool,

    /// Maximum wait time when rate limited (seconds)
    #[arg(long, global = true, default_value = "120")]
    pub max_rate_limit_wait: u64,

    /// Path to configuration file
    #[arg(short, long, global = true, env = "GDELT_CONFIG")]
    pub config: Option<PathBuf>,

    /// Configuration profile to use
    #[arg(long, global = true)]
    pub profile: Option<String>,

    /// Enable debug output
    #[arg(long, global = true)]
    pub debug: bool,

    /// Enable trace-level logging
    #[arg(long, global = true, conflicts_with = "debug")]
    pub trace: bool,

    /// Show timing information
    #[arg(long, global = true)]
    pub timing: bool,

    /// Print help as JSON (for agents)
    #[arg(long, global = true)]
    pub help_json: bool,
}

impl GlobalArgs {
    /// Get the effective output format
    pub fn effective_output_format(&self) -> OutputFormat {
        if self.json {
            OutputFormat::Json
        } else if self.jsonl {
            OutputFormat::Jsonl
        } else if self.csv {
            OutputFormat::Csv
        } else if self.table {
            OutputFormat::Table
        } else if self.markdown {
            OutputFormat::Markdown
        } else {
            self.output
        }
    }

    /// Check if output should be pretty-printed
    pub fn should_pretty_print(&self) -> bool {
        if self.compact {
            return false;
        }
        if self.pretty {
            return true;
        }
        // Default to pretty for TTY
        atty::is(atty::Stream::Stdout)
    }
}

/// Output format options
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    /// Auto-detect based on TTY (table for TTY, json otherwise)
    #[default]
    Auto,
    /// JSON output
    Json,
    /// JSON Lines (streaming)
    Jsonl,
    /// CSV output
    Csv,
    /// Table output (human-readable)
    Table,
    /// Markdown output
    Markdown,
}

/// Top-level commands
#[derive(Subcommand, Debug)]
pub enum Command {
    /// Search and query DOC 2.0 API (news articles)
    #[command(subcommand)]
    Doc(DocCommand),

    /// Search and query GEO 2.0 API (geographic data)
    #[command(subcommand)]
    Geo(GeoCommand),

    /// Search and query TV 2.0 API (television news)
    #[command(subcommand)]
    Tv(TvCommand),

    /// Search and query TV AI API (AI-enhanced TV analysis)
    #[command(subcommand)]
    Tvai(TvAiCommand),

    /// Manage local data downloads
    #[command(subcommand)]
    Data(DataCommand),

    /// Query local events database
    #[command(subcommand)]
    Events(EventsCommand),

    /// Query local GKG (Global Knowledge Graph)
    #[command(subcommand)]
    Gkg(GkgCommand),

    /// Database management
    #[command(subcommand)]
    Db(DbCommand),

    /// Run MCP server (foreground)
    Serve(ServeArgs),

    /// Manage background daemon
    #[command(subcommand)]
    Daemon(DaemonCommand),

    /// Manage Claude Code skill installation
    #[command(subcommand)]
    Skill(SkillCommand),

    /// Analytics and reporting
    #[command(subcommand)]
    Analytics(AnalyticsCommand),

    /// Configuration management
    #[command(subcommand)]
    Config(ConfigCommand),

    /// Schema introspection (for agents)
    #[command(subcommand)]
    Schema(SchemaCommand),

    /// Enrich articles with GKG metadata and optionally fetch full text
    Enrich(EnrichArgs),

    /// Generate shell completions
    Completions(CompletionsArgs),
}

// ============================================================================
// DOC 2.0 API Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum DocCommand {
    /// Search for articles
    Search(DocSearchArgs),
    /// Get timeline data (volume/tone over time)
    Timeline(DocTimelineArgs),
    /// Generate word cloud data
    Wordcloud(DocWordcloudArgs),
    /// List available GKG themes
    Themes(DocThemesArgs),
}

#[derive(Args, Debug)]
pub struct DocSearchArgs {
    /// Search query (supports GDELT query syntax)
    pub query: String,

    /// Time span to search (e.g., "24h", "7d", "3m")
    #[arg(short, long, default_value = "24h")]
    pub timespan: String,

    /// Start datetime (YYYYMMDDHHMMSS), overrides timespan
    #[arg(long)]
    pub start: Option<String>,

    /// End datetime (YYYYMMDDHHMMSS)
    #[arg(long)]
    pub end: Option<String>,

    /// Maximum records to return
    #[arg(short = 'n', long, default_value = "75")]
    pub max_records: u32,

    /// Sort order
    #[arg(short, long, value_enum, default_value = "hybrid-rel")]
    pub sort: SortOrder,

    /// Filter by source language (ISO 639-1)
    #[arg(short, long)]
    pub lang: Option<String>,

    /// Filter by source country (FIPS code)
    #[arg(long)]
    pub country: Option<String>,

    /// Filter by domain
    #[arg(short, long)]
    pub domain: Option<String>,

    /// Filter by GKG theme
    #[arg(long)]
    pub theme: Option<String>,

    /// Minimum tone score (-10 to 10)
    #[arg(long)]
    pub tone_min: Option<f64>,

    /// Maximum tone score (-10 to 10)
    #[arg(long)]
    pub tone_max: Option<f64>,

    /// Enrich results with GKG metadata (themes, persons, orgs, tone)
    #[arg(long)]
    pub enrich: bool,

    /// Fetch full article text (slow, use sparingly)
    #[arg(long)]
    pub fetch_text: bool,

    /// Concurrent fetch limit for article text
    #[arg(long, default_value = "5")]
    pub fetch_concurrency: usize,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SortOrder {
    /// Most recent first
    DateDesc,
    /// Oldest first
    DateAsc,
    /// Most negative tone first
    ToneDesc,
    /// Most positive tone first
    ToneAsc,
    /// Hybrid relevance
    HybridRel,
}

#[derive(Args, Debug)]
pub struct DocTimelineArgs {
    /// Search query
    pub query: String,

    /// Timeline type
    #[arg(short, long, value_enum, default_value = "vol")]
    pub mode: TimelineMode,

    /// Time span to analyze
    #[arg(short, long, default_value = "30d")]
    pub timespan: String,

    /// Smoothing window (1-30)
    #[arg(long)]
    pub smooth: Option<u8>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum TimelineMode {
    /// Volume percentage
    Vol,
    /// Raw article counts
    VolRaw,
    /// Average tone
    Tone,
    /// Language breakdown
    Lang,
    /// Source country breakdown
    SourceCountry,
}

#[derive(Args, Debug)]
pub struct DocWordcloudArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "24h")]
    pub timespan: String,
}

#[derive(Args, Debug)]
pub struct DocThemesArgs {
    /// Filter themes by pattern
    #[arg(short, long)]
    pub filter: Option<String>,
}

// ============================================================================
// GEO 2.0 API Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum GeoCommand {
    /// Search with geographic context
    Search(GeoSearchArgs),
    /// Get point data for locations
    Points(GeoPointsArgs),
    /// Generate heatmap data
    Heatmap(GeoHeatmapArgs),
    /// Country/region aggregation
    Aggregate(GeoAggregateArgs),
}

#[derive(Args, Debug)]
pub struct GeoSearchArgs {
    /// Search query
    pub query: String,

    /// Time span (max 7 days)
    #[arg(short, long, default_value = "24h")]
    pub timespan: String,

    /// Filter by location name
    #[arg(long)]
    pub location: Option<String>,

    /// Filter by country code
    #[arg(long)]
    pub country: Option<String>,

    /// Maximum points to return
    #[arg(short = 'n', long, default_value = "250")]
    pub max_points: u32,
}

#[derive(Args, Debug)]
pub struct GeoPointsArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "24h")]
    pub timespan: String,

    /// Geographic resolution (0=all, 1=no countries, 2=cities only)
    #[arg(long, default_value = "0")]
    pub resolution: u8,
}

#[derive(Args, Debug)]
pub struct GeoHeatmapArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,
}

#[derive(Args, Debug)]
pub struct GeoAggregateArgs {
    /// Search query
    pub query: String,

    /// Aggregation level
    #[arg(short, long, value_enum, default_value = "country")]
    pub level: AggregationLevel,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum AggregationLevel {
    Country,
    Adm1,
}

// ============================================================================
// TV 2.0 API Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum TvCommand {
    /// Search TV captions
    Search(TvSearchArgs),
    /// Get video clips
    Clips(TvClipsArgs),
    /// TV coverage timeline
    Timeline(TvTimelineArgs),
    /// List stations
    Stations(TvStationsArgs),
}

#[derive(Args, Debug)]
pub struct TvSearchArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,

    /// Filter by station
    #[arg(long)]
    pub station: Option<String>,

    /// Maximum results
    #[arg(short = 'n', long, default_value = "250")]
    pub max_records: u32,
}

#[derive(Args, Debug)]
pub struct TvClipsArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "24h")]
    pub timespan: String,
}

#[derive(Args, Debug)]
pub struct TvTimelineArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "30d")]
    pub timespan: String,

    /// Break down by station
    #[arg(long)]
    pub by_station: bool,
}

#[derive(Args, Debug)]
pub struct TvStationsArgs {
    /// Filter by country
    #[arg(short, long)]
    pub country: Option<String>,
}

// ============================================================================
// TV AI API Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum TvAiCommand {
    /// Search AI-analyzed content
    Search(TvAiSearchArgs),
    /// Search by visual concepts
    Concepts(TvAiConceptsArgs),
    /// Search by visual entities
    Visual(TvAiVisualArgs),
}

#[derive(Args, Debug)]
pub struct TvAiSearchArgs {
    /// Search query
    pub query: String,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,

    /// Search in captions
    #[arg(long, default_value = "true")]
    pub captions: bool,

    /// Search in OCR text
    #[arg(long)]
    pub ocr: bool,

    /// Search in ASR transcripts
    #[arg(long)]
    pub asr: bool,
}

#[derive(Args, Debug)]
pub struct TvAiConceptsArgs {
    /// Concept to search
    pub concept: String,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,
}

#[derive(Args, Debug)]
pub struct TvAiVisualArgs {
    /// Visual entity to search
    pub entity: String,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,
}

// ============================================================================
// Data Management Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum DataCommand {
    /// Download historical data
    #[command(subcommand)]
    Download(DownloadCommand),
    /// Sync to latest data
    Sync(DataSyncArgs),
    /// Show download status
    Status(DataStatusArgs),
    /// List available date ranges
    List(DataListArgs),
    /// Delete local data
    Delete(DataDeleteArgs),
}

#[derive(Subcommand, Debug)]
pub enum DownloadCommand {
    /// Download events data
    Events(DownloadEventsArgs),
    /// Download GKG data
    Gkg(DownloadGkgArgs),
    /// Download mentions data
    Mentions(DownloadMentionsArgs),
}

#[derive(Args, Debug)]
pub struct DownloadEventsArgs {
    /// Start date (YYYY-MM-DD)
    #[arg(long)]
    pub start: Option<String>,

    /// End date (YYYY-MM-DD)
    #[arg(long)]
    pub end: Option<String>,

    /// Download all available data
    #[arg(long)]
    pub all: bool,

    /// Number of parallel downloads
    #[arg(long, default_value = "4")]
    pub parallel: u8,
}

#[derive(Args, Debug)]
pub struct DownloadGkgArgs {
    /// Start date (YYYY-MM-DD)
    #[arg(long)]
    pub start: Option<String>,

    /// End date (YYYY-MM-DD)
    #[arg(long)]
    pub end: Option<String>,

    /// GKG version (1 or 2)
    #[arg(long, default_value = "2")]
    pub version: u8,

    /// Number of parallel downloads
    #[arg(long, default_value = "4")]
    pub parallel: u8,
}

#[derive(Args, Debug)]
pub struct DownloadMentionsArgs {
    /// Start date (YYYY-MM-DD)
    #[arg(long)]
    pub start: Option<String>,

    /// End date (YYYY-MM-DD)
    #[arg(long)]
    pub end: Option<String>,

    /// Number of parallel downloads
    #[arg(long, default_value = "4")]
    pub parallel: u8,
}

#[derive(Args, Debug)]
pub struct DataSyncArgs {
    /// Data type to sync
    #[arg(short, long, value_enum)]
    pub data_type: Option<DataType>,

    /// Quick sync: only fetch last 24 hours of data (fast)
    #[arg(long)]
    pub quick: bool,

    /// Number of days to sync (default: sync all available)
    #[arg(long)]
    pub days: Option<u32>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum DataType {
    Events,
    Gkg,
    Mentions,
    All,
}

#[derive(Args, Debug)]
pub struct DataStatusArgs {
    /// Show detailed status
    #[arg(long)]
    pub detailed: bool,
}

#[derive(Args, Debug)]
pub struct DataListArgs {
    /// Data type to list
    #[arg(short, long, value_enum)]
    pub data_type: Option<DataType>,
}

#[derive(Args, Debug)]
pub struct DataDeleteArgs {
    /// Data type to delete
    #[arg(short, long, value_enum)]
    pub data_type: DataType,

    /// Start date
    #[arg(long)]
    pub start: Option<String>,

    /// End date
    #[arg(long)]
    pub end: Option<String>,

    /// Delete all data of this type
    #[arg(long)]
    pub all: bool,
}

// ============================================================================
// Events Query Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum EventsCommand {
    /// Query events from local database
    Query(EventsQueryArgs),
    /// Lookup event by ID
    Lookup(EventsLookupArgs),
    /// Query by actor
    Actors(EventsActorsArgs),
    /// Query by country
    Countries(EventsCountriesArgs),
    /// CAMEO code reference
    #[command(subcommand)]
    Codes(CodesCommand),
}

#[derive(Args, Debug)]
pub struct EventsQueryArgs {
    /// Filter by actor code
    #[arg(short, long)]
    pub actor: Option<String>,

    /// Filter by event code (supports wildcards like "14*")
    #[arg(short, long)]
    pub event_code: Option<String>,

    /// Filter by quad class (1-4)
    #[arg(long)]
    pub quad_class: Option<u8>,

    /// Filter by country
    #[arg(short, long)]
    pub country: Option<String>,

    /// Start date (YYYY-MM-DD)
    #[arg(long)]
    pub start: Option<String>,

    /// End date (YYYY-MM-DD)
    #[arg(long)]
    pub end: Option<String>,

    /// Minimum Goldstein scale (-10 to 10)
    #[arg(long)]
    pub goldstein_min: Option<f64>,

    /// Maximum Goldstein scale
    #[arg(long)]
    pub goldstein_max: Option<f64>,

    /// Maximum results
    #[arg(short = 'n', long, default_value = "100")]
    pub limit: u32,

    /// Offset for pagination
    #[arg(long, default_value = "0")]
    pub offset: u32,
}

#[derive(Args, Debug)]
pub struct EventsLookupArgs {
    /// Global event ID
    pub event_id: String,
}

#[derive(Args, Debug)]
pub struct EventsActorsArgs {
    /// Actor code pattern
    pub actor: Option<String>,

    /// Include statistics
    #[arg(long)]
    pub stats: bool,

    /// Limit results
    #[arg(short = 'n', long, default_value = "50")]
    pub limit: u32,
}

#[derive(Args, Debug)]
pub struct EventsCountriesArgs {
    /// Country code
    pub country: Option<String>,

    /// Date range start
    #[arg(long)]
    pub start: Option<String>,

    /// Date range end
    #[arg(long)]
    pub end: Option<String>,
}

#[derive(Subcommand, Debug)]
pub enum CodesCommand {
    /// List CAMEO codes
    List(CodesListArgs),
    /// Search codes by description
    Search(CodesSearchArgs),
    /// Describe a specific code
    Describe(CodesDescribeArgs),
}

#[derive(Args, Debug)]
pub struct CodesListArgs {
    /// Code type (event, actor, country)
    #[arg(short = 't', long, value_enum)]
    pub code_type: Option<CodeType>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CodeType {
    Event,
    Actor,
    Country,
    Ethnic,
    Religion,
}

#[derive(Args, Debug)]
pub struct CodesSearchArgs {
    /// Search pattern
    pub pattern: String,
}

#[derive(Args, Debug)]
pub struct CodesDescribeArgs {
    /// Code to describe
    pub code: String,
}

// ============================================================================
// GKG Query Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum GkgCommand {
    /// Query GKG records
    Query(GkgQueryArgs),
    /// Query by themes
    Themes(GkgThemesArgs),
    /// Query person mentions
    Persons(GkgPersonsArgs),
    /// Query organization mentions
    Organizations(GkgOrganizationsArgs),
    /// Query location mentions
    Locations(GkgLocationsArgs),
}

#[derive(Args, Debug)]
pub struct GkgQueryArgs {
    /// Filter by theme
    #[arg(short, long)]
    pub theme: Option<String>,

    /// Filter by person
    #[arg(short, long)]
    pub person: Option<String>,

    /// Filter by organization
    #[arg(short, long)]
    pub org: Option<String>,

    /// Start date
    #[arg(long)]
    pub start: Option<String>,

    /// End date
    #[arg(long)]
    pub end: Option<String>,

    /// Maximum results
    #[arg(short = 'n', long, default_value = "100")]
    pub limit: u32,
}

#[derive(Args, Debug)]
pub struct GkgThemesArgs {
    /// Theme pattern to search
    pub pattern: Option<String>,

    /// Minimum occurrence count
    #[arg(long, default_value = "10")]
    pub min_count: u32,

    /// Date range start
    #[arg(long)]
    pub start: Option<String>,

    /// Date range end
    #[arg(long)]
    pub end: Option<String>,
}

#[derive(Args, Debug)]
pub struct GkgPersonsArgs {
    /// Person name pattern
    pub pattern: Option<String>,

    /// Minimum occurrence count
    #[arg(long, default_value = "5")]
    pub min_count: u32,

    /// Limit results
    #[arg(short = 'n', long, default_value = "50")]
    pub limit: u32,
}

#[derive(Args, Debug)]
pub struct GkgOrganizationsArgs {
    /// Organization name pattern
    pub pattern: Option<String>,

    /// Minimum occurrence count
    #[arg(long, default_value = "5")]
    pub min_count: u32,

    /// Limit results
    #[arg(short = 'n', long, default_value = "50")]
    pub limit: u32,
}

#[derive(Args, Debug)]
pub struct GkgLocationsArgs {
    /// Location name pattern
    pub pattern: Option<String>,

    /// Filter by country
    #[arg(short, long)]
    pub country: Option<String>,

    /// Limit results
    #[arg(short = 'n', long, default_value = "50")]
    pub limit: u32,
}

// ============================================================================
// Database Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum DbCommand {
    /// Show database statistics
    Stats(DbStatsArgs),
    /// Optimize database
    Vacuum(DbVacuumArgs),
    /// Export data to file
    Export(DbExportArgs),
    /// Import data from file
    Import(DbImportArgs),
    /// Run raw SQL query
    Query(DbQueryArgs),
}

#[derive(Args, Debug)]
pub struct DbStatsArgs {
    /// Show detailed statistics
    #[arg(long)]
    pub detailed: bool,
}

#[derive(Args, Debug)]
pub struct DbVacuumArgs {
    /// Analyze and optimize
    #[arg(long)]
    pub analyze: bool,
}

#[derive(Args, Debug)]
pub struct DbExportArgs {
    /// Table to export
    pub table: String,

    /// Output file path
    #[arg(short, long)]
    pub output: PathBuf,

    /// Export format
    #[arg(short, long, value_enum, default_value = "parquet")]
    pub format: ExportFormat,

    /// Filter query (WHERE clause)
    #[arg(long)]
    pub filter: Option<String>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ExportFormat {
    Parquet,
    Csv,
    Json,
}

#[derive(Args, Debug)]
pub struct DbImportArgs {
    /// Input file path
    pub input: PathBuf,

    /// Target table
    #[arg(short, long)]
    pub table: String,

    /// Import format (auto-detected from extension if not specified)
    #[arg(short, long, value_enum)]
    pub format: Option<ExportFormat>,
}

#[derive(Args, Debug)]
pub struct DbQueryArgs {
    /// SQL query to execute
    pub query: String,
}

// ============================================================================
// Serve & Daemon Commands
// ============================================================================

#[derive(Args, Debug)]
pub struct ServeArgs {
    /// Transport type
    #[arg(short, long, value_enum, default_value = "stdio")]
    pub transport: Transport,

    /// Port for HTTP/SSE transport
    #[arg(short, long, default_value = "8080")]
    pub port: u16,

    /// Host to bind to
    #[arg(long, default_value = "127.0.0.1")]
    pub host: String,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Transport {
    Stdio,
    Sse,
    Http,
}

#[derive(Subcommand, Debug)]
pub enum DaemonCommand {
    /// Start the daemon
    Start(DaemonStartArgs),
    /// Stop the daemon
    Stop,
    /// Restart the daemon
    Restart,
    /// Show daemon status
    Status,
    /// View daemon logs
    Logs(DaemonLogsArgs),
    /// Install as system service
    Install(DaemonInstallArgs),
    /// Uninstall system service
    Uninstall,
    /// Run daemon (internal use)
    #[command(hide = true)]
    Run,
}

#[derive(Args, Debug)]
pub struct DaemonStartArgs {
    /// Enable MCP server
    #[arg(long, default_value = "true")]
    pub mcp: bool,

    /// Enable background sync
    #[arg(long)]
    pub sync: bool,

    /// HTTP port
    #[arg(long, default_value = "8080")]
    pub port: u16,
}

#[derive(Args, Debug)]
pub struct DaemonLogsArgs {
    /// Number of lines to show
    #[arg(short = 'n', long, default_value = "50")]
    pub tail: u32,

    /// Follow log output
    #[arg(short, long)]
    pub follow: bool,
}

#[derive(Args, Debug)]
pub struct DaemonInstallArgs {
    /// Service manager type
    #[arg(long, value_enum)]
    pub service_type: Option<ServiceType>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ServiceType {
    Systemd,
    Launchd,
}

// ============================================================================
// Skill Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum SkillCommand {
    /// Install Claude Code skill
    Install(SkillInstallArgs),
    /// Uninstall skill
    Uninstall,
    /// Update skill files
    Update,
    /// Show skill status
    Status,
}

#[derive(Args, Debug)]
pub struct SkillInstallArgs {
    /// Install for current project only
    #[arg(long)]
    pub project: bool,

    /// Force overwrite existing skill
    #[arg(short, long)]
    pub force: bool,
}

// ============================================================================
// Analytics Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum AnalyticsCommand {
    /// Trend analysis
    Trends(AnalyticsTrendsArgs),
    /// Entity extraction
    Entities(AnalyticsEntitiesArgs),
    /// Sentiment analysis
    Sentiment(AnalyticsSentimentArgs),
    /// Compare topics (A vs B)
    Compare(AnalyticsCompareArgs),
    /// Generate reports
    #[command(subcommand)]
    Report(ReportCommand),
}

#[derive(Args, Debug)]
pub struct AnalyticsTrendsArgs {
    /// Topic(s) to analyze
    pub topics: Vec<String>,

    /// Data source
    #[arg(short, long, value_enum, default_value = "doc")]
    pub source: AnalyticsSource,

    /// Time span
    #[arg(short, long, default_value = "30d")]
    pub timespan: String,

    /// Granularity
    #[arg(short, long, value_enum, default_value = "day")]
    pub granularity: Granularity,

    /// Normalize to percentage
    #[arg(long)]
    pub normalize: bool,

    /// Detect anomalies
    #[arg(long)]
    pub detect_anomalies: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum AnalyticsSource {
    Doc,
    Tv,
    Events,
    Gkg,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Granularity {
    Hour,
    Day,
    Week,
    Month,
}

#[derive(Args, Debug)]
pub struct AnalyticsEntitiesArgs {
    /// Data source
    #[arg(short, long, value_enum, default_value = "doc")]
    pub source: AnalyticsSource,

    /// Entity type
    #[arg(short, long, value_enum, default_value = "all")]
    pub entity_type: EntityTypeArg,

    /// Minimum occurrence count
    #[arg(long, default_value = "5")]
    pub min_count: u32,

    /// Maximum entities to return
    #[arg(short = 'n', long, default_value = "50")]
    pub limit: u32,

    /// Time span
    #[arg(short, long, default_value = "7d")]
    pub timespan: String,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum EntityTypeArg {
    Person,
    Organization,
    Location,
    Actor,
    Theme,
    All,
}

#[derive(Args, Debug)]
pub struct AnalyticsSentimentArgs {
    /// Topic to analyze
    pub topic: String,

    /// Aggregation dimension
    #[arg(short, long, value_enum, default_value = "time")]
    pub dimension: SentimentDimension,

    /// Time span
    #[arg(short, long, default_value = "30d")]
    pub timespan: String,

    /// Granularity (for time dimension)
    #[arg(short, long, value_enum, default_value = "day")]
    pub granularity: Granularity,

    /// Compare with another topic
    #[arg(long)]
    pub compare_with: Option<String>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SentimentDimension {
    Time,
    Region,
    Source,
    Entity,
}

#[derive(Args, Debug)]
pub struct AnalyticsCompareArgs {
    /// First topic
    pub topic_a: String,

    /// Second topic
    pub topic_b: String,

    /// Time span
    #[arg(short, long, default_value = "30d")]
    pub timespan: String,
}

#[derive(Subcommand, Debug)]
pub enum ReportCommand {
    /// Generate daily report
    Daily(ReportArgs),
    /// Generate weekly report
    Weekly(ReportArgs),
    /// Generate custom report
    Custom(ReportCustomArgs),
}

#[derive(Args, Debug)]
pub struct ReportArgs {
    /// Topics to include
    #[arg(short, long)]
    pub topics: Vec<String>,

    /// Output file
    #[arg(short, long)]
    pub output: Option<PathBuf>,
}

#[derive(Args, Debug)]
pub struct ReportCustomArgs {
    /// Start date
    #[arg(long)]
    pub start: String,

    /// End date
    #[arg(long)]
    pub end: String,

    /// Topics to include
    #[arg(short, long)]
    pub topics: Vec<String>,

    /// Output file
    #[arg(short, long)]
    pub output: Option<PathBuf>,
}

// ============================================================================
// Enrich Command
// ============================================================================

#[derive(Args, Debug)]
pub struct EnrichArgs {
    /// Article URL(s) to enrich
    #[arg(required_unless_present = "stdin")]
    pub urls: Vec<String>,

    /// Read URLs from stdin (one per line)
    #[arg(long)]
    pub stdin: bool,

    /// Fetch full article text
    #[arg(long)]
    pub fetch_text: bool,

    /// Concurrent fetch limit
    #[arg(long, default_value = "5")]
    pub concurrency: usize,
}

// ============================================================================
// Config Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum ConfigCommand {
    /// Show current configuration
    Show,
    /// Get a configuration value
    Get(ConfigGetArgs),
    /// Set a configuration value
    Set(ConfigSetArgs),
    /// Reset configuration to defaults
    Reset,
    /// Validate configuration file
    Validate,
}

#[derive(Args, Debug)]
pub struct ConfigGetArgs {
    /// Configuration key
    pub key: String,
}

#[derive(Args, Debug)]
pub struct ConfigSetArgs {
    /// Configuration key
    pub key: String,
    /// Value to set
    pub value: String,
}

// ============================================================================
// Schema Commands
// ============================================================================

#[derive(Subcommand, Debug)]
pub enum SchemaCommand {
    /// List all commands
    Commands,
    /// Get schema for a specific command
    Command(SchemaCommandArgs),
    /// Get output schema for a command
    Output(SchemaOutputArgs),
    /// List all exit codes
    Codes,
    /// List MCP tool definitions
    Tools,
}

#[derive(Args, Debug)]
pub struct SchemaCommandArgs {
    /// Command name (e.g., "doc search")
    pub command: String,
}

#[derive(Args, Debug)]
pub struct SchemaOutputArgs {
    /// Command name
    pub command: String,
}

// ============================================================================
// Completions Command
// ============================================================================

#[derive(Args, Debug)]
pub struct CompletionsArgs {
    /// Shell to generate completions for
    #[arg(value_enum)]
    pub shell: Shell,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Shell {
    Bash,
    Zsh,
    Fish,
    PowerShell,
}