pvoutput-client 0.0.3

Client for the PVOutput.org API
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
//! Parameters for the various endpoints.

use std::{collections::HashMap, fmt::Display};

use jiff::civil::{Date, Time};
use serde::{Serialize, Serializer};
use serde_repr::Serialize_repr;

use crate::types::Conditions;

/// Parameters for the [`get_status`](crate::Client::get_status) endpoint.
#[derive(Debug, Serialize, Clone, Default)]
pub struct GetStatusParams {
	/// Date to retrieve status for.
	#[serde(rename = "d", serialize_with = "jiff_ymd")]
	pub date: Option<Date>,

	/// Time to retrieve status for.
	#[serde(rename = "t", serialize_with = "jiff_hhmm")]
	pub time: Option<Time>,

	/// Return [history](crate::Client::get_status_history) results in ascending order.
	#[serde(rename = "asc", serialize_with = "bool_int")]
	pub ascending: bool,

	/// Number of results to return when making a [history request](crate::Client::get_status_history), up to a maximum
	/// of **288** (one day of data).
	///
	/// Defaults to **30**.
	pub limit: Option<u16>,

	/// If set, only statuses after this time will be returned.
	#[serde(serialize_with = "jiff_hhmm")]
	pub from: Option<Time>,

	/// If set, only statuses before this time will be returned.
	#[serde(serialize_with = "jiff_hhmm")]
	pub to: Option<Time>,

	/// Return extended data.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "ext", serialize_with = "bool_int")]
	pub extended_data: bool,

	/// System ID to retrieve status for.
	/// If unset, the [`Client`](crate::Client)'s authenticated system is used.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "sid1")]
	pub system_id: Option<u32>,
}

#[derive(Debug, Serialize, Clone, Default)]
pub(crate) struct GetStatusParamsOuter {
	#[serde(flatten)]
	pub params: GetStatusParams,
	#[serde(serialize_with = "bool_int")]
	pub h: bool,
	#[serde(serialize_with = "bool_int")]
	pub stats: bool,
}

impl GetStatusParamsOuter {
	pub const fn new(params: GetStatusParams, h: bool, stats: bool) -> Self { Self { params, h, stats } }
}

/// Parameters for the [`get_statistics`](crate::Client::get_statistics) endpoint.
#[derive(Debug, Serialize, Clone, Default)]
pub struct GetStatisticsParams {
	/// Date to measure statistics from.
	#[serde(rename = "df")]
	pub date_from: Option<Date>,

	/// Date to measure statistics to.
	#[serde(rename = "dt")]
	pub date_to: Option<Date>,

	/// Return consumption data.
	///
	/// This information is only available to the system owner.
	/// Requesting data for another system via the `system_id` parameter will not work.
	#[serde(rename = "c", serialize_with = "bool_int")]
	pub consumption: bool,

	/// Return credit and debit data.
	///
	/// This information is only available to the system owner.
	/// Requesting data for another system via the `system_id` parameter will not work.
	#[serde(rename = "crdr", serialize_with = "bool_int")]
	pub credit_and_debit: bool,

	/// System ID to retrieve statistics for.
	/// If unset, the [`Client`](crate::Client)'s authenticated system is used.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "sid1")]
	pub system_id: Option<u32>,
}

/// Parameters for the [`get_system`](crate::Client::get_system) endpoint.
#[derive(Debug, Serialize, Clone, Default)]
#[allow(clippy::struct_excessive_bools)]
pub struct GetSystemParams {
	/// Return information about the system's secondary array if one is present.
	#[serde(rename = "array2", serialize_with = "bool_int")]
	pub secondary_array: bool,

	/// Return information about the system's tariffs.
	#[serde(serialize_with = "bool_int")]
	pub tariffs: bool,

	/// Return a list of the system's teams.
	#[serde(serialize_with = "bool_int")]
	pub teams: bool,

	/// Return monthly estimates for the system.
	#[serde(rename = "est", serialize_with = "bool_int")]
	pub monthly_estimates: bool,

	/// Return the system's donation count.
	#[serde(serialize_with = "bool_int")]
	pub donations: bool,

	/// System ID to retrieve information for.
	/// If unset, the [`Client`](crate::Client)'s authenticated system is used.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	pub system_id: Option<u32>,

	/// Return extended data.
	#[serde(rename = "ext", serialize_with = "bool_int")]
	pub extended_data: bool,
}

impl GetSystemParams {
	/// Creates a new [`GetSystemParams`] with all fields set to `true`.
	#[must_use]
	pub const fn all() -> Self {
		Self {
			secondary_array: true,
			tariffs: true,
			teams: true,
			monthly_estimates: true,
			donations: true,
			system_id: None,
			extended_data: true,
		}
	}

	/// Creates a new [`GetSystemParams`] for the given system with all fields set to `true`.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[must_use]
	pub const fn all_for_system(system: u32) -> Self {
		Self {
			system_id: Some(system),
			..Self::all()
		}
	}
}

/// Parameters for the [`get_outputs`](crate::Client::get_outputs),
/// [`get_aggregate_outputs`](crate::Client::get_aggregate_outputs),
/// and [`get_team_outputs`](crate::Client::get_team_outputs) endpoints.
#[derive(Debug, Serialize, Clone, Default)]
pub struct GetOutputParams {
	/// Date to retrieve outputs from.
	#[serde(rename = "df", serialize_with = "jiff_ymd")]
	pub date_from: Option<Date>,

	/// Date to retrieve outputs to.
	#[serde(rename = "dt", serialize_with = "jiff_ymd")]
	pub date_to: Option<Date>,

	/// Maximum number of outputs to retrieve.
	/// Limited to **50** for non-donors and **150** for [donors](https://pvoutput.org/help/donations.html).
	pub limit: Option<u8>,

	/// System ID to retrieve outputs for.
	/// If unset, the [`Client`](crate::Client)'s authenticated system is used.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "sid1")]
	pub system_id: Option<u32>,

	/// Retrieve insolation data.
	/// Not supported for [team](crate::Client::get_team_outputs) or
	/// [aggregate outputs](crate::Client::get_aggregate_outputs).
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(serialize_with = "bool_int")]
	pub insolation: bool,

	/// Retrieve time of export data.
	/// Not supported for [team outputs](crate::Client::get_team_outputs).
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "timeofexport", serialize_with = "bool_int")]
	pub time_of_export: bool,
}

/// Aggregation level for [`get_aggregate_outputs`](crate::Client::get_aggregate_outputs).
#[derive(Copy, Clone, Debug, Serialize, PartialEq, Eq, Hash)]
pub enum Aggregation {
	#[serde(rename = "m")]
	Monthly,

	#[serde(rename = "y")]
	Yearly,
}

#[derive(Debug, Serialize, Clone, Default)]
pub(crate) struct GetOutputParamsOuter {
	#[serde(flatten)]
	pub params: GetOutputParams,

	pub a: Option<Aggregation>,
	pub tid: Option<u32>,
}

/// Parameters for the [`get_extended`](crate::Client::get_extended) endpoint.
#[derive(Debug, Serialize, Clone, Default)]
pub struct GetExtendedParams {
	/// Start of the date range to retrieve extended data for.
	#[serde(rename = "df")]
	pub date_from: Option<Date>,

	/// End of the date range to retrieve extended data for.
	#[serde(rename = "dt")]
	pub date_to: Option<Date>,

	/// Maximum number of outputs to retrieve. Limited to **fifty**.
	pub limit: Option<u8>,
}

/// Parameters for the [`get_insolation`](crate::Client::get_insolation) endpoint.
#[derive(Debug, Serialize, Clone, Default)]
pub struct GetInsolationParams {
	/// Date to retrieve insolation data for.
	///
	/// If not set, today's date will be used.
	#[serde(rename = "d", serialize_with = "jiff_ymd")]
	pub date: Option<Date>,

	/// Timezone to use for insolation calculation.
	///
	/// If not set, the system's timezone will be used.
	/// If the system doesn't have a timezone, UTC will be used as a fallback.
	#[serde(rename = "tz")]
	pub timezone: Option<String>,

	/// Latitude and longitude to use for insolation calculation.
	///
	/// If not set, the system's latitude and longitude will be used.
	/// If the system doesn't have location information, the system's postcode's latitude and longitude will be used.
	#[serde(rename = "ll", serialize_with = "lat_long")]
	pub location: Option<(f32, f32)>,

	/// System to retrieve insolation data for.
	///
	/// If unset, the [`Client`](crate::Client)'s authenticated system is used.
	#[serde(rename = "sid1")]
	pub system_id: Option<u32>,
}

/// Parameters for the [`search`](crate::Client::search) endpoint.
#[derive(Debug, Serialize, Clone)]
pub struct SearchParams {
	/// Search query.
	///
	/// See the [PVOutput docs](https://pvoutput.org/help/searching.html#searching) for further information.
	#[serde(rename = "q")]
	pub query: String,

	/// Latitude and longitude to use as the point of origin for
	/// [distance searches](https://pvoutput.org/help/searching.html#:~:text=Distance%20(System)).
	#[serde(rename = "ll", serialize_with = "lat_long")]
	pub location: Option<(f32, f32)>,

	/// Return country names alongside postcodes.
	#[serde(rename = "country", serialize_with = "bool_int")]
	pub country_names: bool,

	/// Filter results by country code.
	///
	/// Required for postcode distance searches (e.g. `q=4000 20km`)
	pub country_code: Option<CountryCode>,

	/// Only return systems that were last seen this number of days ago or fewer.
	pub seen: Option<u32>,
}

impl SearchParams {
	/// Create a new search query.
	///
	/// `location`, `country_code`, and `seen` will be set to `None`, and `country_names` will be set to `false`.
	pub fn new(query: impl Into<String>) -> Self {
		Self {
			query: query.into(),
			location: None,
			country_names: false,
			country_code: None,
			seen: None,
		}
	}
}

/// Country codes for use with [`SearchParams`].
// documented here: https://pvoutput.org/help/api_specification.html#country-codes
#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CountryCode {
	/// Australia.
	#[serde(rename = "au")]
	Australia,

	/// Belgium (België).
	#[serde(rename = "be")]
	Belgium,

	/// Denmark (Danmark).
	#[serde(rename = "dk")]
	Denmark,

	/// Italy (Italia).
	#[serde(rename = "it")]
	Italy,

	/// The Netherlands (Nederland).
	#[serde(rename = "nl")]
	Netherlands,

	/// The United Kingdom of Great Britain and Northern Ireland.
	#[serde(rename = "uk")]
	UnitedKingdom,

	/// The United States of America.
	#[serde(rename = "us")]
	UnitedStates,
}

/// Parameters for the [`add_outputs`](crate::Client::add_outputs) endpoint.
///
/// # Example
/// [`AddOutputParams::new`] can be used to create a parameter struct with all other fields set to `None`.
/// This can be used to easily create parameters with only one or two fields set:
/// ```rust
/// use pvoutput_client::types::{Conditions, params::AddOutputParams};
/// use jiff::civil::Date;
///
/// let params = AddOutputParams {
///   generated: Some(1_500),
///   conditions: Some(Conditions::Cloudy),
///   ..AddOutputParams::new(Date::constant(2025, 09, 22))
/// };
/// ```
#[derive(Serialize, Clone, Debug)]
pub struct AddOutputParams {
	/// Output date.
	///
	/// Must be after 2000-01-01 and not in the future.
	#[serde(serialize_with = "jiff_ymd_direct")]
	pub date: Date,

	/// Power generated in watt-hours.
	/// This is *required* if an output does not yet exist for this date.
	pub generated: Option<u32>,

	/// Power exported in watt-hours.
	pub exported: Option<u32>,

	/// Peak power output in watts.
	pub peak: Option<u32>,

	/// The time at which the peak output was recorded.
	/// Seconds will be truncated -- `11:15:05` becomes `11:15`.
	#[serde(serialize_with = "jiff_hhmm")]
	pub peak_time: Option<Time>,

	/// The day's weather conditions.
	pub conditions: Option<Conditions>,

	/// The minimum recorded temperature in degrees Celsius.
	///
	/// If set, a maximum temperature must also be provided, and the minimum temperature must be lower than the maximum
	/// temperature.
	///
	/// Both temperatures must be between -100.0 and 100.0.
	pub min_temp: Option<f32>,

	/// The maximum recorded temperature in degrees Celsius.
	///
	/// If set, a minimum temperature must also be provided, and the minimum temperature must be lower than the maximum
	/// temperature.
	///
	/// Both temperatures must be between -100.0 and 100.0.
	pub max_temp: Option<f32>,

	/// A comment.
	// TODO: handle semicolons and newlines in comments
	pub comment: Option<String>,

	/// The amount of energy imported during the peak tariff in watt-hours.
	pub import_peak: Option<u32>,

	/// The amount of energy imported during the off-peak tariff in watt-hours.
	pub import_off_peak: Option<u32>,

	/// The amount of energy imported during the shoulder tariff in watt-hours.
	pub import_shoulder: Option<u32>,

	/// The amount of energy imported during the high-shoulder tariff in watt-hours.
	pub import_high_shoulder: Option<u32>,

	/// Energy consumption in watt-hours.
	///
	/// Limited to 999,999,999 Wh.
	pub consumption: Option<u32>,

	/// The amount of energy exported during the peak tariff in watt-hours.
	pub export_peak: Option<u32>,

	/// The amount of energy exported during the off-peak tariff in watt-hours.
	pub export_off_peak: Option<u32>,

	/// The amount of energy exported during the shoulder tariff in watt-hours.
	pub export_shoulder: Option<u32>,

	/// The amount of energy exported during the high-shoulder tariff in watt-hours.
	pub export_high_shoulder: Option<u32>,
}

impl AddOutputParams {
	/// Creates a new [`AddOutputParams`] for the given date with all other fields set to `None`.
	#[must_use]
	pub const fn new(date: Date) -> Self {
		Self {
			date,
			generated: None,
			exported: None,
			peak: None,
			peak_time: None,
			conditions: None,
			min_temp: None,
			max_temp: None,
			comment: None,
			import_peak: None,
			import_off_peak: None,
			import_shoulder: None,
			import_high_shoulder: None,
			consumption: None,
			export_peak: None,
			export_off_peak: None,
			export_shoulder: None,
			export_high_shoulder: None,
		}
	}
}

/// Common parameters for the [`add_status`](crate::Client::add_status),
/// [`add_batch_status`](crate::Client::add_batch_status), and
/// [`add_batch_status_net`](crate::Client::add_batch_status_net) endpoints.
#[allow(clippy::too_long_first_doc_paragraph)]
#[derive(Clone, Debug, Serialize)]
pub struct AddStatusCommon {
	/// The date for this status.
	///
	/// Must be within the past **fourteen days**, or the past **ninety days** for
	/// accounts with [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "d", serialize_with = "jiff_ymd_direct")]
	pub date: Date,

	/// The time for this status.
	///
	/// Times will be rounded to the nearest configured
	/// [status interval](https://pvoutput.org/help/live_data.html#live-configuration-status-interval).
	#[serde(rename = "t", serialize_with = "jiff_hhmm_direct")]
	pub time: Time,

	/// Energy generation in watt-hours.
	///
	/// This field is **required** when using the batch status endpoint.
	#[serde(rename = "v1")]
	pub energy_generation: Option<u32>,

	/// Power generation in watts.
	#[serde(rename = "v2")]
	pub power_generation: Option<i32>,

	/// Energy consumption in watt-hours.
	///
	/// Limited to **200,000 Wh** for free accounts, or **999,999,999 Wh** for
	/// accounts with [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "v3")]
	pub energy_consumption: Option<u32>,

	/// Power consumption in watts.
	///
	/// Limited to **100,000 W** for free accounts, or **2,000,000 W** for
	/// accounts with [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "v4")]
	pub power_consumption: Option<i32>,

	/// Temperature in degrees Celsius.
	#[serde(rename = "v5")]
	pub temperature: Option<f32>,

	/// Voltage in volts.
	#[serde(rename = "v6")]
	pub voltage: Option<f32>,
}

impl AddStatusCommon {
	/// Creates a new [`AddStatusCommon`] for the given date and time with all other fields set to `None`.
	#[must_use]
	pub const fn new(date: Date, time: Time) -> Self {
		Self {
			date,
			time,
			energy_generation: None,
			power_generation: None,
			energy_consumption: None,
			power_consumption: None,
			temperature: None,
			voltage: None,
		}
	}
}

/// Extended parameters for use with the [`AddStatusParams`] and [`AddBatchStatusParams`] structs.
#[derive(Clone, Debug, Serialize, Default)]
pub struct AddExtendedParams {
	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 1.
	#[serde(rename = "v7")]
	pub extended_value_1: Option<f32>,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 2.
	#[serde(rename = "v8")]
	pub extended_value_2: Option<f32>,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 3.
	#[serde(rename = "v9")]
	pub extended_value_3: Option<f32>,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 4.
	#[serde(rename = "v10")]
	pub extended_value_4: Option<f32>,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 5.
	#[serde(rename = "v11")]
	pub extended_value_5: Option<f32>,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 6.
	#[serde(rename = "v12")]
	pub extended_value_6: Option<f32>,
}

/// Parameters for the [`add_status`](crate::Client::add_status) endpoint.
#[derive(Clone, Debug, Serialize)]
pub struct AddStatusParams {
	/// Parameters common to the [`add_status`](crate::Client::add_status) and
	/// [`add_batch_status`](crate::Client::add_batch_status) endpoints.
	#[serde(flatten)]
	pub common: AddStatusCommon,

	/// Whether to process this status as a cumulative status, and if so, which fields are cumulative.
	#[serde(rename = "c1")]
	pub cumulative_flag: CumulativeFlag,

	/// Whether to process this status as net data.
	///
	/// See the [PVOutput docs](https://pvoutput.org/help/api_specification.html#net-data) for further information.
	#[serde(rename = "n", serialize_with = "bool_int")]
	pub net_data: bool,

	/// Extended data.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(flatten)]
	pub extended_data: Option<AddExtendedParams>,

	/// A comment.
	///
	/// Limited to a maximum of thirty characters.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(rename = "m1")]
	pub message: Option<String>,

	/// Battery information.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(flatten)]
	pub battery: Option<AddBatteryParams>,
}

impl AddStatusParams {
	/// Creates a new instance of [`AddStatusParams`] with the given common parameters and all other fields set to
	/// `None`.
	#[must_use]
	pub const fn new(common: AddStatusCommon) -> Self {
		Self {
			common,
			cumulative_flag: CumulativeFlag::False,
			net_data: false,
			extended_data: None,
			message: None,
			battery: None,
		}
	}
}

impl From<AddStatusCommon> for AddStatusParams {
	fn from(common: AddStatusCommon) -> Self { Self::new(common) }
}

#[derive(Clone, Debug, Serialize, Default)]
pub struct AddBatteryParams {
	/// Battery power in watts.
	/// A positive value indicates charging either from generation or load (consumption).
	/// A negative value indicates discharging.
	#[serde(rename = "b1")]
	pub power: i32,

	/// State of charge as a percentage.
	#[serde(rename = "b2")]
	pub state_of_charge: Option<f32>,

	/// Usable battery size in watt-hours.
	#[serde(rename = "b3")]
	pub size: Option<u32>,

	/// Lifetime charge in watt-hours.
	#[serde(rename = "b4")]
	pub lifetime_charge: Option<u32>,

	/// Lifetime discharge in watt-hours.
	#[serde(rename = "b5")]
	pub lifetime_discharge: Option<u32>,

	/// Battery state.
	#[serde(rename = "b6")]
	pub state: Option<BatteryState>,
}

/// Battery state.
/// For use with [`AddStatusParams`].
///
/// [PVOutput docs](https://pvoutput.org/help/api_specification.html#state-codes)
// note to future me: deriving repr(int) starts at zero and automatically increments.
// see https://doc.rust-lang.org/reference/items/enumerations.html#implicit-discriminants
#[derive(Copy, Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize_repr)]
#[repr(u8)]
pub enum BatteryState {
	Invalid,
	#[default]
	Standby,
	ThermalManagement,
	Enabled,
	Fault,

	/// User defined. Corresponds to `b2=5`.
	UserDefinedA,

	/// User defined. Corresponds to `b2=6`.
	UserDefinedB,

	/// User defined. Corresponds to `b2=7`.
	UserDefinedC,

	/// User defined. Corresponds to `b2=8`.
	UserDefinedD,

	/// User defined. Corresponds to `b2=9`.
	UserDefinedE,
}

/// Parameters for the [`add_batch_status`](crate::Client::add_batch_status) endpoint.
#[derive(Clone, Debug, Serialize)]
pub struct AddBatchStatusParams {
	/// Parameters common to the [`add_status`](crate::Client::add_status) and
	/// [`add_batch_status`](crate::Client::add_batch_status) endpoints.
	#[serde(flatten)]
	pub common: AddStatusCommon,

	/// Extended data.
	///
	/// Requires [donation status](https://pvoutput.org/help/donations.html).
	#[serde(flatten)]
	pub extended_data: Option<AddExtendedParams>,
}

impl AddBatchStatusParams {
	/// Creates a new [`AddBatchStatusParams`].
	#[must_use]
	pub const fn new(common: AddStatusCommon, extended_data: Option<AddExtendedParams>) -> Self {
		Self { common, extended_data }
	}
}

impl From<AddStatusCommon> for AddBatchStatusParams {
	fn from(common: AddStatusCommon) -> Self {
		Self {
			common,
			extended_data: None,
		}
	}
}

/// Parameters for the [`add_batch_status_net`](crate::Client::add_batch_status_net) endpoint.
#[derive(Clone, Debug, Serialize)]
pub struct AddNetBatchStatusParams {
	/// The date for this status.
	#[serde(serialize_with = "jiff_ymd_direct")]
	pub date: Date,

	/// The time for this status.
	///
	/// Times will be rounded to the nearest configured
	/// [status interval](https://pvoutput.org/help/live_data.html#live-configuration-status-interval).
	#[serde(serialize_with = "jiff_hhmm_direct")]
	pub time: Time,

	spacer_a: (),

	/// Power exported in watts.
	pub power_exported: u32,

	spacer_b: (),

	/// Power imported in watts.
	pub power_imported: u32,
}

impl AddNetBatchStatusParams {
	/// Creates a new [`AddNetBatchStatusParams`] with the provided fields.
	#[must_use]
	pub const fn new(date: Date, time: Time, power_exported: u32, power_imported: u32) -> Self {
		Self {
			date,
			time,
			spacer_a: (),
			power_exported,
			spacer_b: (),
			power_imported,
		}
	}
}

/// Whether to process a status as cumulative, and if so, which of its fields are cumulative.
#[derive(Clone, Debug, Copy, Default, Serialize, Hash, Eq, PartialEq)]
pub enum CumulativeFlag {
	/// This status is not cumulative.
	#[serde(rename = "0")]
	#[default]
	False,

	/// The energy generation and consumption values for this status are lifetime cumulative values.
	#[serde(rename = "1")]
	Both,

	/// The energy generation value for this status is lifetime cumulative.
	#[serde(rename = "2")]
	Generation,

	/// The energy consumption value for this status is lifetime cumulative.
	#[serde(rename = "3")]
	Consumption,
}

/// Parameters for the [`post_system`](crate::Client::post_system) endpoint.
///
/// Updating extended data variables requires [donation status](https://pvoutput.org/help/donations.html).
#[derive(Clone, Debug, Default)]
pub struct PostSystemParams {
	/// A new name for the system.
	/// Limited to thirty characters.
	pub name: Option<String>,

	/// Extended data variables.
	pub(crate) extended_variables: HashMap<ExtendedVariable, ExtendedVariableUpdate>,
}

impl PostSystemParams {
	/// Creates a new [`PostSystemParams`].
	#[must_use]
	pub fn new() -> Self { Self::default() }

	/// Creates a new [`PostSystemParams`] with the provided `name` and no extended data variables.
	#[must_use]
	pub fn new_rename(name: String) -> Self {
		Self {
			name: Some(name),
			extended_variables: HashMap::new(),
		}
	}

	/// Adds a new extended variable update.
	///
	/// If there is already an update for this variable, it will be replaced with the provided update.
	///
	/// # Example
	/// ```rust
	/// use pvoutput_client::types::params::{ExtendedVariable, ExtendedVariableUpdate, PostSystemParams};
	///
	/// let mut post = PostSystemParams::default();
	/// let update = ExtendedVariableUpdate {
	///   label: Some(String::from("Wind speed")),
	///   unit: Some(String::from("m/s")),
	///   ..Default::default()
	/// };
	/// post.add_update(ExtendedVariable::V7, update);
	///
	/// assert_eq!(
	///   post.get_update(ExtendedVariable::V7).map(|u| u.label.as_deref()).flatten(),
	///   Some("Wind speed")
	/// );
	/// assert!(post.get_update(ExtendedVariable::V8).is_none());
	/// ```
	pub fn add_update(&mut self, variable: ExtendedVariable, update: ExtendedVariableUpdate) -> &mut Self {
		self.extended_variables.insert(variable, update);
		self
	}

	/// Gets the update for the given extended variable, if any.
	#[must_use]
	pub fn get_update(&self, variable: ExtendedVariable) -> Option<&ExtendedVariableUpdate> {
		self.extended_variables.get(&variable)
	}
}

/// An update to an [extended data variable](https://pvoutput.org/help/extended_data.html).
///
/// Any omitted fields will use the previously set values if this extended variable already exists, or the default
/// values if it doesn't.
///
/// # Default colours
/// | Variable | Colour |
/// |:--------:|--------|
/// |    v7    | 339933 |
/// |    v8    | ccff66 |
/// |    v9    | efcf21 |
/// |    v10   | ff5555 |
/// |    v11   | 0a72b1 |
/// |    v12   | dd5fc9 |
#[derive(Debug, Clone, Default)]
pub struct ExtendedVariableUpdate {
	/// A label for this extended variable.
	/// Limited to twenty characters.
	///
	/// This field is *required* if this is a new extended variable.
	pub label: Option<String>,

	/// A unit for this extended variable.
	/// Limited to ten characters.
	///
	/// This field is *required* if this is a new extended variable.
	pub unit: Option<String>,

	/// A colour to use for this extended variable, formatted as six lowercase hexadecimal digits without leading
	/// `#` -- for example, `ff0000` for bright red.
	pub colour: Option<String>,

	/// The axis to use for this extended variable.
	/// Must be between zero and five.
	/// The default is zero.
	///
	/// Parameters placed on the same axis are shown on the same graph scale.
	pub axis: Option<u8>,

	/// How to graph this extended variable.
	/// The default is [`Graph::Line`].
	pub graph: Option<Graph>,
}

/// An [extended data variable](https://pvoutput.org/help/extended_data.html) identifier.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum ExtendedVariable {
	/// The first extended variable (`v7`).
	V7 = 7,

	/// The second extended variable (`v8`).
	V8 = 8,

	/// The third extended variable (`v9`).
	V9 = 9,

	/// The fourth extended variable (`v10`).
	V10 = 10,

	/// The fifth extended variable (`v11`).
	V11 = 11,

	/// The sixth extended variable (`v12`).
	V12 = 12,
}

impl TryFrom<u8> for ExtendedVariable {
	type Error = u8;

	fn try_from(value: u8) -> Result<Self, Self::Error> {
		match value {
			7 => Ok(Self::V7),
			8 => Ok(Self::V8),
			9 => Ok(Self::V9),
			10 => Ok(Self::V10),
			11 => Ok(Self::V11),
			12 => Ok(Self::V12),
			_ => Err(value),
		}
	}
}

/// How to graph an extended variable.
#[derive(Copy, Clone, Debug, Default, Serialize, Hash, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Graph {
	/// Use an area graph.
	Area,

	/// Use a line graph.
	#[default]
	Line,
}

impl Display for Graph {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Area => write!(f, "area"),
			Self::Line => write!(f, "line"),
		}
	}
}

#[derive(Serialize)]
pub(crate) struct DeleteStatusParams {
	#[serde(serialize_with = "jiff_ymd_direct")]
	pub d: Date,

	#[serde(serialize_with = "jiff_hhmm")]
	pub t: Option<Time>,
}

// custom serialiser functions

/// Serialises an [`Option<Date>`] to a string in the format "yyyymmdd".
#[allow(clippy::ref_option)]
fn jiff_ymd<S>(value: &Option<Date>, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	if let Some(value) = value {
		s.serialize_str(value.strftime("%Y%m%d").to_string().as_str())
	} else {
		s.serialize_none()
	}
}

/// Serialises a [`Date`] to a string in the format "yyyymmdd".
#[allow(clippy::ref_option)]
fn jiff_ymd_direct<S>(value: &Date, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	jiff_ymd(&Some(*value), s)
}

/// Serialises an [`Option<Time>`] to a string in the format "hh:mm".
#[allow(clippy::ref_option)]
fn jiff_hhmm<S>(value: &Option<Time>, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	if let Some(value) = value {
		s.serialize_str(value.strftime("%H:%M").to_string().as_str())
	} else {
		s.serialize_none()
	}
}

/// Serialises a [`Time`] to a string in the format "hh:mm".
#[allow(clippy::ref_option)]
fn jiff_hhmm_direct<S>(value: &Time, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	jiff_hhmm(&Some(*value), s)
}

/// Serialises a [`bool`] to a string "1" or "0".
#[allow(clippy::trivially_copy_pass_by_ref)]
fn bool_int<S>(value: &bool, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	s.serialize_u8(u8::from(*value))
}

/// Serialises a latitude and longitude pair to a comma-separated string.
#[allow(clippy::ref_option)]
fn lat_long<S>(value: &Option<(f32, f32)>, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	if let Some(value) = value {
		s.serialize_str(format!("{},{}", value.0, value.1).as_str())
	} else {
		s.serialize_none()
	}
}