plox 0.3.7

Turn messy logs into clean graphs. Plot fields or regex matches over time, mark events, count occurrences — all from your terminal.
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
//! Builds the command-line argument structure specifically for the 'graph' subcommand.
//! This module defines the various flags, options, and arguments that control how graphs are generated.
//!
//! This complex logic here is necessary because Clap alone cannot support ordered, repeated, multi-flag patterns
//! like: `--plot ... --panel --event ... --plot ...`.  

use crate::{cli::EXTRA_HELP, data_source_cli_builder::build_data_source_cli, graph_config::*};
use clap::{
	Arg, ArgAction, ArgMatches, Command, CommandFactory, FromArgMatches, Parser, ValueEnum,
	value_parser,
};
use serde::{Deserialize, Serialize};
use std::{
	collections::BTreeMap,
	num::{ParseFloatError, ParseIntError},
	path::{Path, PathBuf},
	str::{FromStr, ParseBoolError},
};
use tracing::{error, trace};

pub const LOG_TARGET: &str = "graph_cli_builder";

#[derive(Debug, thiserror::Error)]
pub enum Error {
	#[error("Parse int error: {0}")]
	ParseIntError(#[from] ParseIntError),
	#[error("Parse int error: {0}")]
	ParseBoolError(#[from] ParseBoolError),
	#[error("Parse float error: {0}")]
	ParseFloatError(#[from] ParseFloatError),
	#[error("CLI parsing error: {0}")]
	GeneralCliParseError(String),
	#[error("CLI parsing error: {0}")]
	GraphCliParseError(#[from] crate::data_source_cli_builder::Error),
	#[error("Unknown panel param {0:?}")]
	UnknownPanelParam(String),
	#[error("Invalid line source {0:?}")]
	InvalidLineSource(String),
	#[error("Missing line data source")]
	MissingLineDataSource,
	#[error("Unknown line param {0:?}")]
	UnknownLineParam(String),
}

impl From<String> for Error {
	fn from(error: String) -> Self {
		Error::GeneralCliParseError(error)
	}
}

/// Helper for deserializing a GraphConfig which may contain extra options from
/// [`GraphInOutContext`]
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GraphConfigWithContext {
	#[serde(flatten)]
	pub config: GraphConfig,
	#[serde(flatten)]
	pub context: OutputGraphContext,
	#[serde(flatten)]
	pub input: InputFilesContext,
}

impl GraphConfigWithContext {
	pub fn load_from_file(path: &Path) -> Result<Self, crate::error::Error> {
		let content = std::fs::read_to_string(path).map_err(|error| {
			error!(?error, "Reading toml error");
			crate::error::Error::IoError(format!("{}", path.display()), error)
		})?;
		toml::from_str(&content).map_err(|e| {
			let r = annotate_toml_error(&e, &content, &path.display().to_string());
			error!("{r}");
			e.into()
		})
	}
}

/// A builder for incrementally constructing a [`Line`].
///
/// This builder allows you to specify the line's data source via [`DataSource`]
/// (e.g. [`DataSource::FieldValue`], [`DataSource::EventValue`]) and then apply
/// styling or configuration parameters (e.g. color, axis) via [`LineParams`].
#[derive(Debug, Default)]
pub struct LineBuilder {
	/// Optional core data source for the line.
	line: Option<DataSource>,
	params: LineParams,
}

impl LineBuilder {
	/// Create a new empty builder.
	fn new() -> Self {
		Self { ..Self::default() }
	}

	/// Set the data source for this line to a particular [`DataSource`].
	///
	/// This overwrites any previously set data source.
	fn line(mut self, data_source: DataSource) -> Self {
		self.line = Some(data_source);
		self
	}

	/// Apply one styling/config parameter.
	///
	/// This can be called multiple times to layer parameters. If a parameter
	/// is duplicated, the last call wins.
	fn apply_param(mut self, param: LineParam) -> Self {
		match param {
			LineParam::LineColor(c) => self.params.line_color = Some(c),
			LineParam::YAxis(y) => self.params.yaxis = Some(y),
			LineParam::MarkerType(mt) => self.params.marker_type = Some(mt),
			LineParam::MarkerColor(mc) => self.params.marker_color = Some(mc),
			LineParam::InputFileName(name) => self.params.file_name = Some(name),
			LineParam::InputFileId(id) => self.params.file_id = Some(id),
			LineParam::PlotStyle(style) => self.params.style = style,
			LineParam::LineWidth(w) => self.params.line_width = Some(w),
			LineParam::MarkerSize(w) => self.params.marker_size = w,
			LineParam::DashStyle(s) => self.params.dash_style = Some(s),
			LineParam::Title(s) => self.params.title = Some(s),
		}
		self
	}

	/// Finalize and return the fully constructed [`Line`], if a data source was set.
	///
	/// Returns [`None`] if no [`DataSource`] was specified.
	fn build(self) -> Result<Line, Error> {
		if self.params.file_name.is_some() && self.params.file_id.is_some() {
			return Err(Error::InvalidLineSource(format!(
				"file-name {} and file-id {} cannot be used together.",
				self.params.file_name.unwrap().display(),
				self.params.file_id.unwrap()
			)));
		}
		self.line
			.ok_or(Error::MissingLineDataSource)
			.map(|data_source| Line { data_source, params: self.params })
	}
}

/// A builder for incrementally constructing a [`Panel`].
///
/// This builder allows to specify configuration parameters via applying [`PanelParams`].
#[derive(Debug, Default)]
pub struct PanelBuilder {
	lines: Vec<Line>,
	params: PanelParams,
}

impl Panel {
	pub fn builder() -> PanelBuilder {
		PanelBuilder::new()
	}
}

impl PanelBuilder {
	/// Create a new empty builder.
	fn new() -> Self {
		Self::default()
	}

	/// Apply one styling/config parameter.
	///
	/// This can be called multiple times to set different parameters. If a parameter
	/// is defined multiple times, the last value takes precedence.
	fn apply_param(mut self, param: PanelParam) -> Self {
		match param {
			PanelParam::PanelTitle(t) => self.params.panel_title = Some(t),
			PanelParam::Height(h) => self.params.height = Some(h),
			PanelParam::YAxisScale(ys) => self.params.yaxis_scale = Some(ys),
			PanelParam::Legend(l) => self.params.legend = Some(l),
			PanelParam::TimeRangeMode(r) => self.params.time_range_mode = Some(r),
		}
		self
	}

	/// Sets lines contained within panel.
	pub fn with_lines(mut self, lines: Vec<Line>) -> Self {
		self.lines = lines.clone();
		self
	}

	/// Finalize and return the constructed [`Panel`].
	pub fn build(self) -> Panel {
		Panel { lines: self.lines, params: self.params }
	}
}

#[derive(Debug)]
enum Event {
	NewPanel,
	NewLine(DataSource),
	ApplyLineParam(LineParam),
	ApplyPanelParam(PanelParam),
}

/// Represents a styling or configuration parameter that can be applied to a line.
///
/// These parameters do not change the data source; rather, they adjust how the line
/// is drawn (color, axis, marker style), or from which log file the data is taken.
///
/// Intended to be used while parsing the command line, for event based config building.
#[derive(Debug, PartialEq)]
enum LineParam {
	/// See: [`LineParams::file_name`]
	InputFileName(PathBuf),

	/// See: [`LineParams::title`]
	Title(String),

	/// See: [`LineParams::file_id`]
	InputFileId(usize),

	/// See: [`LineParams::style`]
	PlotStyle(PlotStyle),

	/// See: [`LineParams::line_width`]
	LineWidth(LineWidth),

	/// See: [`LineParams::line_color`]
	LineColor(Color),

	/// See: [`LineParams::dash_style`]
	DashStyle(DashStyle),

	/// See: [`LineParams::yaxis`]
	YAxis(YAxis),

	/// See: [`LineParams::marker_type`]
	MarkerType(MarkerType),

	/// See: [`LineParams::marker_color`]
	MarkerColor(Color),

	/// See: [`LineParams::marker_size`]
	MarkerSize(MarkerSize),
}

impl LineParam {
	fn from_flag(flag: &str, val: &[String]) -> Result<Self, Error> {
		Ok(match flag {
			"title" => Self::Title(val[0].clone()),
			"file_name" => Self::InputFileName(PathBuf::from(&val[0])),
			"file_id" => Self::InputFileId(val[0].parse::<usize>()?),
			"style" => Self::PlotStyle(<PlotStyle as ValueEnum>::from_str(&val[0], false)?),
			"line_width" => Self::LineWidth(LineWidth::from_str(&val[0])?),
			"line_color" => Self::LineColor(<Color as ValueEnum>::from_str(&val[0], false)?),
			"dash_style" => Self::DashStyle(<DashStyle as ValueEnum>::from_str(&val[0], false)?),
			"yaxis" => Self::YAxis(YAxis::from_str(&val[0], false)?),
			"marker_type" => Self::MarkerType(<MarkerType as ValueEnum>::from_str(&val[0], false)?),
			"marker_color" => Self::MarkerColor(<Color as ValueEnum>::from_str(&val[0], false)?),
			"marker_size" => Self::MarkerSize(MarkerSize::from_str(&val[0])?),
			_ => Err(Error::UnknownLineParam(flag.to_string()))?,
		})
	}
}

#[derive(Debug, PartialEq)]
enum PanelParam {
	/// See: [`PanelParams::panel_title`]
	PanelTitle(String),

	/// See: [`PanelParams::height`]
	Height(f64),

	/// See: [`PanelParams::yaxis_scale`]
	YAxisScale(AxisScale),

	/// See: [`PanelParams::legend`]
	Legend(bool),

	/// See: [`PanelParams::time_range_mode`]
	TimeRangeMode(PanelRangeMode),
}

impl PanelParam {
	fn from_flag(flag: &str, val: &[String]) -> Result<Self, Error> {
		Ok(match flag {
			"panel_title" => Self::PanelTitle(val[0].to_string()),
			"height" => Self::Height(val[0].parse::<f64>()?),
			"yaxis_scale" => Self::YAxisScale(AxisScale::from_str(&val[0], false)?),
			"legend" => Self::Legend(val[0].parse::<bool>()?),
			"time_range_mode" => Self::TimeRangeMode(PanelRangeMode::from_str(&val[0], false)?),
			_ => Err(Error::UnknownPanelParam(flag.to_string()))?,
		})
	}
}

impl GraphConfig {
	fn parse_params_for_command<F>(
		command: Command,
		matches: &ArgMatches,
		mut build_event: F,
	) -> Result<(), Error>
	where
		F: FnMut(usize, &str, &[String]) -> Result<(), Error>,
	{
		// Process each line parameter flag
		let line_args_ids = {
			let arg_ids: Vec<_> = command.get_arguments().map(|arg| arg.get_id().clone()).collect();
			arg_ids
		};

		for id in line_args_ids {
			trace!(target: LOG_TARGET, "processing id: {:?}", id);
			if let Some(values) = matches.get_raw_occurrences(id.as_str()) {
				let entries = matches.indices_of(id.as_str()).unwrap();
				for (index, val) in entries.zip(values.clone()) {
					let param_args = val.into_iter().try_fold(Vec::new(), |mut acc, s| {
						let converted = s
							.to_str()
							.ok_or_else(|| {
								Error::GeneralCliParseError(format!(
									"Params string conversion (?) mess: {:?}",
									values
								))
							})?
							.to_string();
						acc.push(converted);
						Ok::<Vec<String>, Error>(acc)
					})?;

					build_event(index, id.as_str(), &param_args[..])?;
				}
			}
		}
		Ok(())
	}

	/// Builds a `GraphConfig` by parsing CLI arguments in the order they appear.
	///
	/// This function enables flexible, order-sensitive CLI composition by:
	/// - Tracking user-provided arguments as logical **events** (e.g. `--panel`, `--plot`)
	/// - Preserving original argument order using match indices
	/// - Incrementally constructing panels and lines using a builder-style approach
	///
	/// This is necessary because Clap alone cannot support ordered, repeated, multi-flag patterns
	/// like: `--plot ... --panel --event ... --plot ...`.  
	/// By interpreting arguments as a linear sequence of graphing instructions,
	/// this method supports expressive CLI layouts without sacrificing ergonomics or structure.
	///
	/// Used internally to construct a `GraphConfig` from `clap::ArgMatches`.
	pub fn try_from_matches(matches: &ArgMatches) -> Result<Self, Error> {
		let mut events: BTreeMap<usize, Event> = BTreeMap::new();

		trace!(target: LOG_TARGET, "try_from_matches: {:#?}", matches);

		// Index panels
		if let Some(indices) = matches.indices_of("panel") {
			trace!(target: LOG_TARGET, "panel indices: {:#?}", indices);
			for i in indices {
				events.insert(i, Event::NewPanel);
			}
		}

		// Process plots, events, events-counts and event-deltas
		let all_data_sources = DataSource::get_cli_ids();
		for id in &all_data_sources {
			if let Some(plot_values) = matches.get_occurrences::<String>(id) {
				let mut indices = matches.indices_of(id).unwrap();
				for plot_value in plot_values {
					let args: Vec<_> = plot_value.collect();

					let args_len = args.len();
					let index = indices.nth(args_len - 1).unwrap();
					events.insert(index, Event::NewLine(DataSource::try_from_flag(id, &args)?));
				}
			}
		}

		Self::parse_params_for_command(
			DummyCliLineArgs::command(),
			matches,
			|index, id, param_args| -> Result<(), Error> {
				let param = LineParam::from_flag(id, param_args)?;
				events.insert(index, Event::ApplyLineParam(param));
				Ok(())
			},
		)?;

		Self::parse_params_for_command(
			DummyCliPanelArgs::command(),
			matches,
			|index, id, param_args| -> Result<(), Error> {
				let param = PanelParam::from_flag(id, param_args)?;
				events.insert(index, Event::ApplyPanelParam(param));
				Ok(())
			},
		)?;

		//todo: could be refactored to some nicer flow.
		let mut panels = vec![];
		let mut current_lines = vec![];
		let mut current_line_builder: Option<LineBuilder> = None;
		let mut current_panel_builder: Option<PanelBuilder> = Some(PanelBuilder::new());

		trace!(target: LOG_TARGET, ?events, "building graph config");
		for (_, event) in events {
			match event {
				Event::NewPanel => {
					if let Some(line) = current_line_builder.take().map(|b| b.build()) {
						current_lines.push(line?);
					}

					if let Some(panel_builder) = current_panel_builder.take() {
						panels.push(panel_builder.with_lines(current_lines).build());
						current_panel_builder = Some(PanelBuilder::new());
					}

					current_lines = vec![];
				},
				Event::NewLine(data_source) => {
					if let Some(line) = current_line_builder.take().map(|b| b.build()) {
						current_lines.push(line?);
					}
					current_line_builder = Some(LineBuilder::new().line(data_source));
				},
				Event::ApplyLineParam(param) => {
					if let Some(builder) = current_line_builder {
						current_line_builder = Some(builder.apply_param(param))
					} else {
						return Err(Error::GeneralCliParseError(format!(
							"Line parameter {:?} has no associated line.",
							param
						)));
					}
				},
				Event::ApplyPanelParam(param) => {
					if let Some(builder) = current_panel_builder {
						current_panel_builder = Some(builder.apply_param(param))
					} else {
						return Err(Error::GeneralCliParseError(format!(
							"Panel parameter {:?} has no associated panel.",
							param
						)));
					}
				},
			}
		}

		if let Some(line) = current_line_builder.take().map(|b| b.build()) {
			current_lines.push(line?);
		}

		if !current_lines.is_empty() {
			if let Some(panel_builder) = current_panel_builder.take() {
				panels.push(panel_builder.with_lines(current_lines).build());
			} else {
				return Err(Error::GeneralCliParseError(
					"No panel builder left? Logic error.".into(),
				));
			}
		}

		Ok(GraphConfig { panels })
	}
}

/// Dummy helper wrapper for `CommandFactory`
///
/// Used for injecting line parameters args.
#[derive(Parser, Debug)]
#[command(name = "dummy")]
struct DummyCliLineArgs {
	#[command(flatten)]
	line_args: LineParams,
}

/// Dummy helper wrapper for `CommandFactory`
///
/// Used for injecting panel parameters args.
#[derive(Parser, Debug)]
#[command(name = "dummy")]
struct DummyCliPanelArgs {
	#[command(flatten)]
	panel_args: PanelParams,
}

#[derive(Parser, Debug)]
#[command(name = "dummy")]
struct DummyCliSharedGraphContext {
	#[command(flatten)]
	ctx: GraphFullContext,
}

/// Constructs the command-line interface (CLI) for the graph command.
///
/// This CLI setup uses a custom strategy to reuse argument definitions and documentation
/// from `clap`-derived enums and structs, while building a flat, flag-based CLI interface.
///
/// - [`DataSource`] is defined as an enum with `#[derive(Subcommand)]`, where each variant (e.g.
///   `EventValue`, `PlotField`) holds documented arguments.
/// - We extract the auto-generated `Command` from Clap using `.command()` and pull out each
///   subcommand’s fields (clap `Arg`s).
/// - These are restructured into regular `--flag <args>` format by preserving:
///   - Help text (`.get_help()`)
///   - Field names as value names (`.get_id()`)
///   - Required/optional status to determine `num_args`
///
/// We also extract argument definitions from additional `#[derive(Args)]` structs (like
/// [`LineParams`]) and inject them into the final `Command` using the same technique.
///
/// ## Why this is needed:
/// - Clap does not support using enums directly for `--flag <args>` style flags.
/// - It also cannot handle repeated flags (e.g. `--plot ... --panel --plot ... --event ...`) in a
///   way that preserves **argument order**, which is important for many use cases like sequential
///   log analysis or layered graphing.
/// - Structs alone cannot express multiple positional groups, or interleaved repeated arguments.
/// - We work around this by:
///   - Using `ArgAction::Append` to collect repeated values
///   - Manually tracking CLI argument **positions** (via `matches.indices_of(...)`) to reconstruct
///     the original user input order (see [`GraphConfig::try_from_matches`]).
///
/// This pattern avoids duplication of documentation, keeps CLI definitions clean,
/// and enables flexible composition of arguments from multiple sources.
pub fn build_cli() -> Command {
	let long_about = r#"
The 'graph' command parses timestamped log files and plots numeric fields, regex captures, events, or deltas over time.

Supports:
- Regex-based value extraction,
- Named fields with optional guards,
- Multiple panels and file-aware layouts.
"#;

	let graph_cmd = Command::new("graph")
		.about("Extract and plot structured data from logs.")
		.long_about(long_about);

	let mut graph_config_cli = build_data_source_cli(graph_cmd);

	// merge all line arguments [`LineParams`]
	{
		let cmd = DummyCliLineArgs::command();
		let args = cmd.get_arguments();

		for arg in args {
			let arg = arg.clone().action(ArgAction::Append).help_heading("Line Options");
			graph_config_cli = graph_config_cli.arg(&arg);
		}
	}
	{
		let cmd = DummyCliPanelArgs::command();
		let args = cmd.get_arguments();

		for arg in args {
			let arg = arg.clone().action(ArgAction::Append).help_heading("Panel Options");
			graph_config_cli = graph_config_cli.arg(&arg);
		}
	}

	{
		let cmd = DummyCliSharedGraphContext::command();
		let args = cmd.get_arguments();

		for arg in args {
			let arg = arg.clone();
			graph_config_cli = graph_config_cli.arg(&arg);
		}
	}

	let graph_config_cli = graph_config_cli
		.arg(
			// Note: flags don't track the position of each occurrence, so we need to emulate
			// flags with value-less options to get the same result.
			Arg::new("panel")
				.long("panel")
				.value_parser(value_parser!(bool))
				.default_missing_value("true")
				.action(ArgAction::Append)
				.num_args(0)
				.help_heading("Panel Options")
				.help("Add new panel to graph"),
		)
		.arg(
			Arg::new("config")
				.long("config")
				.short('c')
				.value_name("FILE")
				.help_heading("Input files")
				.help("Path to TOML config file containing panels layout."),
		);
	const ENV_HELP: &str = color_print::cstr!(
		r#"<bold><underline>Environment variables:</underline></bold>
There are two environment variables controlling behaviour of graph command:
- `PLOX_IMAGE_VIEWER` - the name (or path) of the executable that will be used to display image generated by `gnuplot`.
- `PLOX_BROWSER` - the name (or path) of the executable that will be used to display html generated by plotly backend.
- `PLOX_SKIP_GNUPLOT` - if set, the gnuplot image generation will not be executed, only gnuplot script will be saved.
"#
	);
	graph_config_cli.after_long_help(ENV_HELP.to_string() + EXTRA_HELP)
}

pub fn build_from_matches(
	matches: &ArgMatches,
) -> Result<(GraphConfig, GraphFullContext), crate::error::Error> {
	let mut full_graph_context = GraphFullContext::from_arg_matches(matches).map_err(|e| {
		Error::GeneralCliParseError(format!(
			"SharedGraphContext Instantiation failed. This is bug. {}",
			e
		))
	})?;

	let config = if let Some(config_path) = matches.get_one::<String>("config") {
		let GraphConfigWithContext { config, context, input } =
			GraphConfigWithContext::load_from_file(Path::new(config_path))?;
		let context = GraphFullContext { input_files_ctx: input, output_graph_ctx: context };
		full_graph_context.merge_with_other(context);
		config
	} else {
		GraphConfig::try_from_matches(matches)?
	};

	Ok((config, full_graph_context))
}

/// Intended to be used in test.
#[cfg(test)]
pub fn build_from_cli_args(
	args: Vec<&'static str>,
) -> Result<(GraphConfig, GraphFullContext), crate::error::Error> {
	let full_args: Vec<_> = ["graph"].into_iter().chain(args).collect();
	let matches = build_cli().try_get_matches_from(full_args.clone()).unwrap();
	build_from_matches(&matches)
}

#[cfg(test)]
mod tests {
	use crate::logging::init_tracing_test;

	use super::*;
	use std::path::Path;

	pub struct GraphConfigBuilder {
		panels: Vec<Panel>,
		current_panel: Option<Panel>,
	}

	impl GraphConfigBuilder {
		pub fn new() -> Self {
			GraphConfigBuilder { panels: Vec::new(), current_panel: None }
		}

		pub fn with_panel(mut self, panel: Panel) -> Self {
			if let Some(panel) = self.current_panel.take() {
				self.panels.push(panel);
			}
			self.current_panel = Some(panel);
			self
		}

		pub fn with_default_panel(mut self) -> Self {
			if let Some(panel) = self.current_panel.take() {
				self.panels.push(panel);
			}
			self.current_panel = Some(Panel { lines: Vec::new(), params: Default::default() });
			self
		}

		pub fn with_line(mut self, line: Line) -> Self {
			if let Some(ref mut panel) = self.current_panel {
				panel.lines.push(line);
			} else {
				// If there's no current panel, start a new one and add the line
				self.current_panel = Some(Panel { lines: vec![line], params: Default::default() });
			}
			self
		}

		pub fn build(mut self) -> GraphConfig {
			if let Some(panel) = self.current_panel {
				self.panels.push(panel);
			}
			GraphConfig { panels: self.panels }
		}
	}

	impl LineBuilder {
		pub fn with_event_count_line(mut self, guard: Option<String>, pattern: String) -> Self {
			self.line = Some(DataSource::EventCount { guard, pattern });
			self
		}

		pub fn with_event_value_line(
			mut self,
			guard: Option<String>,
			pattern: String,
			yvalue: f64,
		) -> Self {
			self.line = Some(DataSource::EventValue { guard, pattern, yvalue });
			self
		}

		pub fn with_plot_field_line(mut self, guard: Option<String>, field: String) -> Self {
			self.line = Some(DataSource::FieldValue(FieldCaptureSpec { guard, field }));
			self
		}

		pub fn with_field_value_sum_line(mut self, guard: Option<String>, field: String) -> Self {
			self.line = Some(DataSource::FieldValueSum(FieldCaptureSpec { guard, field }));
			self
		}
	}

	#[test]
	fn test_01() {
		check_ok(
			vec!["--plot", "c1", "d"],
			"tests/test-files/config01.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.build(),
		);
	}
	#[test]
	fn test_02() {
		check_ok(
			vec!["--event-count", "d"],
			"tests/test-files/config02.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_event_count_line(None, "d".into()).build().unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_03() {
		check_ok(
			vec!["--event-count", "c1", "d"],
			"tests/test-files/config03.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_event_count_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_04() {
		check_ok(
			vec!["--event", "d", "101.1"],
			"tests/test-files/config04.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_event_value_line(None, "d".into(), 101.1f64)
						.build()
						.unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_05() {
		check_ok(
			vec!["--event", "c1", "d", "101.1"],
			"tests/test-files/config05.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_event_value_line(Some("c1".into()), "d".into(), 101.1f64)
						.build()
						.unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_06() {
		check_ok(
			vec!["--plot", "c1", "d", "--plot", "xxx"],
			"tests/test-files/config06.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "xxx".into()).build().unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_07() {
		check_ok(
			vec![
				"--plot", "1", "--panel", "--plot", "2", "--panel", "--plot", "3", "--panel",
				"--plot", "4",
			],
			"tests/test-files/config07.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "1".into()).build().unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "2".into()).build().unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "3".into()).build().unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "4".into()).build().unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_08() {
		check_ok(
			vec![
				"--plot", "c1", "d", "--plot", "x", "y", "--panel", "--plot", "1", "A", "--plot",
				"2", "--panel", "--plot", "3", "--plot", "4", "B", "--panel", "--plot", "5",
				"--plot", "6",
			],
			"tests/test-files/config08.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("x".into()), "y".into())
						.build()
						.unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("1".into()), "A".into())
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "2".into()).build().unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "3".into()).build().unwrap(),
				)
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("4".into()), "B".into())
						.build()
						.unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "5".into()).build().unwrap(),
				)
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "6".into()).build().unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_09() {
		check_ok(
			vec!["--plot", "c1", "d", "--plot", "x", "y", "--panel", "--plot", "e"],
			"tests/test-files/config09.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("x".into()), "y".into())
						.build()
						.unwrap(),
				)
				.with_default_panel()
				.with_line(
					LineBuilder::new().with_plot_field_line(None, "e".into()).build().unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_10() {
		check_ok(
			vec!["--plot", "c1", "d", "--line-color", "red"],
			"tests/test-files/config10.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.apply_param(LineParam::LineColor("red".into()))
						.build()
						.unwrap(),
				)
				.build(),
		)
	}
	#[test]
	fn test_11() {
		check_ok(
			vec!["--plot", "c1", "d", "--line-color", "red", "--file-id", "12"],
			"tests/test-files/config11.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("c1".into()), "d".into())
						.apply_param(LineParam::LineColor("red".into()))
						.apply_param(LineParam::InputFileId(12))
						.build()
						.unwrap(),
				)
				.build(),
		)
	}

	#[test]
	fn test_12() {
		check_ok(
			vec![
				"--event",
				"duration",
				"666.0",
				"--file-name",
				"x.log",
				"--yaxis",
				"y2",
				"--line-color",
				"red",
				"--marker-type",
				"circle",
				"--marker-color",
				"blue",
			],
			"tests/test-files/config12.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_event_value_line(None, "duration".into(), 666.0)
						.apply_param(LineParam::LineColor("red".into()))
						.apply_param(LineParam::MarkerType("circle".into()))
						.apply_param(LineParam::MarkerColor("blue".into()))
						.apply_param(LineParam::YAxis(YAxis::Y2))
						.apply_param(LineParam::InputFileName("x.log".into()))
						.build()
						.unwrap(),
				)
				.build(),
		)
	}

	#[test]
	fn test_13() {
		check_ok(
			vec![
				"--panel-title",
				"A nice title",
				"--height",
				"0.3",
				"--yaxis-scale",
				"log",
				"--legend",
				"true",
				"--event",
				"duration",
				"666.0",
			],
			"tests/test-files/config13.toml",
			GraphConfigBuilder::new()
				.with_panel(
					PanelBuilder::new()
						.apply_param(PanelParam::PanelTitle("A nice title".into()))
						.apply_param(PanelParam::Height(0.3))
						.apply_param(PanelParam::YAxisScale(AxisScale::Log))
						.apply_param(PanelParam::Legend(true))
						.build(),
				)
				.with_line(
					LineBuilder::new()
						.with_event_value_line(None, "duration".into(), 666.0)
						.build()
						.unwrap(),
				)
				.build(),
		)
	}

	#[rustfmt::skip]
	fn test_14_input() -> Vec<&'static str> {
		vec![
			//panel 1
			"--panel-title", "Another title", "--height", "0.3", "--yaxis-scale", "log", "--legend", "true",
			//line 1
			"--event", "duration", "666.0",
				"--file-name", "x.log",
				"--title", "LineTitle",
				"--style", "lines-points",
				"--line-width", "2.4",
				"--line-color", "red",
				"--dash-style", "dash-dot",
				"--yaxis", "y2",
				"--marker-type", "circle",
				"--marker-color", "blue",
				"--marker-size", "5.0",
			//line 2
			"--event", "duration", "777.0",
				"--file-name", "y.log",
				"--yaxis", "y",
				"--line-color", "blue",
				"--marker-type", "square",
				"--marker-color", "yellow",
			//panel 2
			"--panel", "--panel-title", "panel2", "--height", "0.5", "--yaxis-scale", "linear", "--legend", "false",
			// line 1
			"--plot", "xxx", "yyy",
				"--file-name", "plot1.log",
				"--style", "lines",
				"--yaxis", "y",
				"--line-color", "red",
				"--marker-type", "circle",
				"--marker-color", "blue",
			// line 2
			"--event-count", "duration",
				"--file-name", "plot2.log",
				"--style", "lines",
				"--yaxis", "y2",
				"--line-color", "dark-turquoise",
				"--marker-type", "dot",
				"--marker-color", "black",
		]
	}

	#[test]
	fn test_14_combo() {
		init_tracing_test();
		check_ok(
			test_14_input(),
			"tests/test-files/config14.toml",
			GraphConfigBuilder::new()
				.with_panel(
					PanelBuilder::new()
						.apply_param(PanelParam::PanelTitle("Another title".into()))
						.apply_param(PanelParam::Height(0.3))
						.apply_param(PanelParam::YAxisScale(AxisScale::Log))
						.apply_param(PanelParam::Legend(true))
						.build(),
				)
				.with_line(
					LineBuilder::new()
						.with_event_value_line(None, "duration".into(), 666.0)
						.apply_param(LineParam::InputFileName("x.log".into()))
						.apply_param(LineParam::Title("LineTitle".into()))
						.apply_param(LineParam::PlotStyle(PlotStyle::LinesPoints))
						.apply_param(LineParam::LineWidth(LineWidth(2.4)))
						.apply_param(LineParam::LineColor(Color::Red))
						.apply_param(LineParam::DashStyle(DashStyle::DashDot))
						.apply_param(LineParam::YAxis(YAxis::Y2))
						.apply_param(LineParam::MarkerType(MarkerType::Circle))
						.apply_param(LineParam::MarkerColor(Color::Blue))
						.apply_param(LineParam::MarkerSize(MarkerSize(5.0)))
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new()
						.with_event_value_line(None, "duration".into(), 777.0)
						.apply_param(LineParam::LineColor("blue".into()))
						.apply_param(LineParam::MarkerType("square".into()))
						.apply_param(LineParam::MarkerColor("yellow".into()))
						.apply_param(LineParam::YAxis(YAxis::Y))
						.apply_param(LineParam::InputFileName("y.log".into()))
						.build()
						.unwrap(),
				)
				.with_panel(
					PanelBuilder::new()
						.apply_param(PanelParam::PanelTitle("panel2".into()))
						.apply_param(PanelParam::Height(0.5))
						.apply_param(PanelParam::YAxisScale(AxisScale::Linear))
						.apply_param(PanelParam::Legend(false))
						.build(),
				)
				.with_line(
					LineBuilder::new()
						.with_plot_field_line(Some("xxx".into()), "yyy".into())
						.apply_param(LineParam::PlotStyle(PlotStyle::Lines))
						.apply_param(LineParam::LineColor("red".into()))
						.apply_param(LineParam::MarkerType("circle".into()))
						.apply_param(LineParam::MarkerColor("blue".into()))
						.apply_param(LineParam::YAxis(YAxis::Y))
						.apply_param(LineParam::InputFileName("plot1.log".into()))
						.build()
						.unwrap(),
				)
				.with_line(
					LineBuilder::new()
						.with_event_count_line(None, "duration".into())
						.apply_param(LineParam::PlotStyle(PlotStyle::Lines))
						.apply_param(LineParam::LineColor("dark-turquoise".into()))
						.apply_param(LineParam::MarkerType("dot".into()))
						.apply_param(LineParam::MarkerColor("black".into()))
						.apply_param(LineParam::YAxis(YAxis::Y2))
						.apply_param(LineParam::InputFileName("plot2.log".into()))
						.build()
						.unwrap(),
				)
				.build(),
		)
	}

	#[test]
	fn test_15() {
		check_ok(
			vec!["--field-value-sum", "c1", "d"],
			"tests/test-files/config15.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_field_value_sum_line(Some("c1".into()), "d".into())
						.build()
						.unwrap(),
				)
				.build(),
		);
	}

	#[test]
	fn test_16() {
		check_ok(
			vec![
				"--field-value-sum",
				"duration",
				"--file-name",
				"x.log",
				"--yaxis",
				"y2",
				"--line-color",
				"red",
				"--marker-type",
				"circle",
				"--marker-color",
				"blue",
			],
			"tests/test-files/config16.toml",
			GraphConfigBuilder::new()
				.with_default_panel()
				.with_line(
					LineBuilder::new()
						.with_field_value_sum_line(None, "duration".into())
						.apply_param(LineParam::LineColor("red".into()))
						.apply_param(LineParam::MarkerType("circle".into()))
						.apply_param(LineParam::MarkerColor("blue".into()))
						.apply_param(LineParam::YAxis(YAxis::Y2))
						.apply_param(LineParam::InputFileName("x.log".into()))
						.build()
						.unwrap(),
				)
				.build(),
		)
	}

	#[test]
	#[should_panic(expected = "invalid value")]
	fn test_e00() {
		check_err(vec!["--plot", "c1", "d", "--line-color", "red", "--file-id", "12x"])
	}

	#[test]
	#[should_panic(expected = "invalid value")]
	fn test_e01() {
		check_err(vec!["--plot", "c1", "d", "--line-color", "red", "--yaxis", "y3"])
	}

	#[test]
	#[should_panic(expected = "Invalid line source")]
	fn test_e02() {
		check_err(vec!["--plot", "c1", "d", "--file-id", "1", "--file-name", "x.log"])
	}

	fn check_err(args: Vec<&str>) {
		let full_args: Vec<_> = ["graph"].iter().chain(args.iter()).cloned().collect();
		let matches = build_cli().try_get_matches_from(full_args.clone());
		trace!("matches: {:#?}", matches);
		if let Ok(matches) = matches {
			let parsed = GraphConfig::try_from_matches(&matches);
			trace!("parsed: {:#?}", parsed);
			panic!("{}", parsed.err().unwrap());
		} else {
			panic!("{}", matches.err().unwrap().render());
		}
	}

	fn check_ok(args: Vec<&str>, config_file: &str, expected: GraphConfig) {
		let full_args: Vec<_> = ["graph"].iter().chain(args.iter()).cloned().collect();
		let matches = build_cli().try_get_matches_from(full_args.clone()).unwrap();
		let parsed = GraphConfig::try_from_matches(&matches).unwrap();

		parsed.save_to_file(Path::new("/tmp/parsed.toml")).unwrap();
		expected.save_to_file(Path::new("/tmp/expected.toml")).unwrap();

		if !Path::new(config_file).exists() {
			parsed.save_to_file(Path::new(config_file)).unwrap();
		}
		let loaded = GraphConfig::load_from_file(Path::new(config_file)).unwrap();
		trace!("loaded: {:#?}", loaded);
		trace!("parsed: {:#?}", parsed);
		trace!("expect: {:#?}", expected);
		trace!("{:#?}", full_args.join(" "));
		assert_eq!(parsed, expected);
		assert_eq!(loaded, expected);
	}
}