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
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
//! API response types.

use jiff::{
	Span, Timestamp,
	civil::{Date, Time},
};
use reqwest::header::HeaderMap;
use serde::{
	Deserialize, Deserializer,
	de::{DeserializeOwned, Error},
};

use crate::types::{Conditions, error::RateLimitError, regions::Region};

/// An API response along with current rate limit information.
#[derive(Debug, Clone)]
pub struct Response<T> {
	/// Data returned by the API.
	pub data: T,

	/// Rate limit information.
	pub rate_limit: RateLimit,
}

impl<T> Response<T> {
	pub(crate) const fn new(data: T, rate_limit: RateLimit) -> Self { Self { data, rate_limit } }
}

/// Rate limit information: the number of requests that can be made per hour, the remaining request count, and the time
/// at which the limit will be reset.
///
/// [PVOutput docs](https://pvoutput.org/help/api_specification.html#http-headers)
#[derive(Debug, Clone)]
pub struct RateLimit {
	/// The total request limit for the hour.
	pub limit: u16,

	/// The remaining requests for the hour.
	pub remaining: u16,

	/// The time at which the rate limit will be reset.
	pub reset: Timestamp,
}

impl RateLimit {
	/// The number of requests that have been used in this hourly block.
	///
	/// # Example
	/// ```rust
	/// use pvoutput_client::types::response::RateLimit;
	/// use jiff::Timestamp;
	/// let rate_limit = RateLimit { limit: 300, remaining: 100, reset: Timestamp::now() };
	/// assert_eq!(rate_limit.used(), 200);
	/// ```
	#[must_use]
	pub const fn used(&self) -> u16 {
		debug_assert!(self.remaining <= self.limit);
		self.limit - self.remaining
	}
}

impl TryFrom<&HeaderMap> for RateLimit {
	type Error = RateLimitError;

	fn try_from(value: &HeaderMap) -> Result<Self, Self::Error> {
		if let (Some(limit), Some(remaining), Some(reset)) = (
			value.get("X-Rate-Limit-Limit"),
			value.get("X-Rate-Limit-Remaining"),
			value.get("X-Rate-Limit-Reset"),
		) {
			let limit = limit.to_str()?.parse()?;
			let remaining = remaining.to_str()?.parse()?;
			let reset = Timestamp::from_second(reset.to_str()?.parse()?)?;

			debug_assert!(remaining <= limit);

			Ok(Self {
				limit,
				remaining,
				reset,
			})
		} else {
			Err(RateLimitError::MissingValues)
		}
	}
}

/// Information returned by the [`get_status`](crate::Client::get_status) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Status {
	/// The date of the status.
	pub date: Date,

	/// The time of the status.
	pub time: Time,

	/// Energy generation in watt-hours.
	pub energy_generation: f32,

	/// Power generation in watts.
	pub power_generation: f32,

	/// Energy consumption in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub energy_consumption: Option<f32>,

	/// Power consumption in watts.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub power_consumption: Option<f32>,

	/// Normalised output in kilowatts per kilowatt.
	// TODO: what does that even mean?
	pub normalised_output: f32,

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

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

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 1.
	#[serde(default)]
	pub extended_value_1: Option<f32>,

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

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

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

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

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

/// Historic status.
///
/// Returned by the [`get_status_history`](crate::Client::get_status_history) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct History {
	/// The date of the status.
	pub date: Date,

	/// The time of the status.
	pub time: Time,

	/// Energy generation in watt-hours.
	pub energy_generation: f32,

	/// Energy efficiency in kilowatt-hours per kilowatt-hour.
	pub energy_efficiency: f32,

	/// Instantaneous power generation in watts.
	pub instantaneous_power: f32,

	/// Average power generation in watts.
	pub average_power: f32,

	/// Normalised output in kilowatts per kilowatt.
	// TODO: what does that even mean?
	pub normalised_output: f32,

	/// Energy consumption in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub energy_consumption: Option<f32>,

	/// Power consumption in watts.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub power_consumption: Option<f32>,

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

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

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 1.
	#[serde(default)]
	pub extended_value_1: Option<f32>,

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

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

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

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

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

/// Daily status summary.
///
/// Returned by the [`get_status_daily`](crate::Client::get_status_daily) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct DailyStatus {
	/// Energy generation in watt-hours.
	pub energy_generation: f32,

	/// Power generation in watts.
	pub power_generation: f32,

	/// Peak power generation in watts.
	pub peak_power_generation: f32,

	/// Time at which the peak power generation occurred.
	pub peak_time: Time,

	/// Energy consumption data.
	#[serde(skip)]
	pub consumption: Option<DailyConsumption>,

	/// Temperature data.
	#[serde(skip)]
	pub temperatures: Option<DailyTemperatures>,
}

/// Daily power and energy consumption data.
///
/// Part of a [`DailyStatus`] response.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct DailyConsumption {
	/// Energy consumption in watt-hours.
	pub energy_consumption: Option<f32>,

	/// Power consumption in watts.
	pub power_consumption: Option<f32>,

	/// Standby power consumption(?)
	pub standby_power_consumption: Option<f32>,

	/// Standby power time(?)
	pub standby_power_time: Option<Time>,
}

/// Daily temperature data.
///
/// Part of a [`DailyStatus`] response.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct DailyTemperatures {
	/// Lowest recorded temperature in degrees Celsius.
	pub lowest_temperature: Option<f32>,

	/// Highest recorded temperature in degrees Celsius.
	pub highest_temperature: Option<f32>,

	/// Average temperature in degrees Celsius.
	pub average_temperature: Option<f32>,
}

/// System statistics.
///
/// Returned by the [`get_statistics`](crate::Client::get_statistics) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Statistics {
	/// Energy generated in watt-hours.
	pub energy_generated: u64,

	/// Energy exported in watt-hours.
	pub energy_exported: u64,

	/// Average energy generation in watt-hours.
	pub average_energy_generation: u32,

	/// Minimum energy generation in watt-hours.
	pub minimum_energy_generation: u32,

	/// Maximum energy generation in watt-hours.
	pub maximum_energy_generation: u32,

	/// Average efficiency in kilowatt-hours per kilowatt-hour.
	pub average_efficiency: f32,

	/// Number of outputs recorded.
	pub outputs: u32,

	/// Date from which these data were measured.
	pub date_from: Date,

	/// Date to which these data were measured.
	pub date_to: Date,

	/// The best daily energy efficiency in kilowatt-hours per kilowatt-hour.
	pub record_efficiency: f32,

	/// The date of the best daily energy efficiency.
	pub record_date: Date,

	/// Energy consumption data.
	#[serde(skip)]
	pub consumption: Option<ConsumptionStatistics>,

	/// Credit amount.
	#[serde(skip)]
	pub credit: Option<f32>,

	/// Debit amount.
	#[serde(skip)]
	pub debit: Option<f32>,
}

/// Consumption statistics.
/// All figures are in watt-hours.
///
/// Part of a [`Statistics`] response.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ConsumptionStatistics {
	/// Energy consumed.
	pub energy_consumed: u64,

	/// Peak energy import.
	pub peak_energy_import: u32,

	/// Off-peak energy import.
	pub off_peak_energy_import: u32,

	/// Shoulder energy import.
	pub shoulder_energy_import: u32,

	/// High-shoulder energy import.
	pub high_shoulder_energy_import: u32,

	/// Average consumption.
	pub average_consumption: u32,

	/// Minimum consumption.
	pub minimum_consumption: u32,

	/// Maximum consumption.
	pub maximum_consumption: u32,
}

/// Common system information.
///
/// Returned by the [`get_system`](crate::Client::get_system) and
/// [`get_favourites`](crate::Client::get_favourites) endpoints.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct System {
	/// System name.
	pub name: String,

	/// System size in watts.
	pub size: u64,

	/// Postcode or Zipcode.
	pub postcode: Option<String>,

	/// Number of panels in the primary array.
	pub panels: Option<u32>,

	/// Power of each panel in the primary array in watts.
	pub panel_power: Option<u32>,

	/// Panel brand.
	pub brand: Option<String>,

	/// Number of inverters.
	pub inverters: Option<u32>,

	/// Inverter power in watts.
	pub inverter_power: Option<u64>,

	/// Inverter brand.
	pub inverter_brand: Option<String>,

	/// Orientation of the primary solar array.
	pub orientation: Option<Orientation>,

	/// Tilt of the primary solar array.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub tilt: Option<f32>,

	/// System shade level.
	#[serde(deserialize_with = "nullable")]
	pub shade: Option<Shade>,

	/// System installation date.
	pub install_date: Option<Date>,

	/// System location latitude.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub latitude: Option<f32>,

	/// System location longitude.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub longitude: Option<f32>,
}

/// Full system information.
///
/// Returned by the [`get_system`](crate::Client::get_system) endpoint.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct FullSystem {
	/// Base system information.
	#[serde(skip)]
	pub system: System,

	/// Status update frequency in minutes.
	pub status_interval: Option<u32>,

	/// Number of panels in the secondary array.
	#[serde(default)]
	pub secondary_panels: Option<u32>,

	/// Power of each panel in the secondary array in watts.
	#[serde(default)]
	pub secondary_panel_power: Option<u32>,

	/// Orientation of the secondary solar array.
	#[serde(deserialize_with = "nullable", default)]
	pub secondary_orientation: Option<Orientation>,

	/// Tilt of the secondary solar array.
	#[serde(deserialize_with = "opt_nan_f32", default)]
	pub secondary_tilt: Option<f32>,

	/// Tariff information.
	#[serde(skip)]
	pub tariffs: Tariffs,

	/// Participating teams.
	#[serde(skip)]
	pub teams: Vec<u32>,

	/// Number of donations.
	#[serde(skip)]
	pub donations: u32,

	/// Extended data.
	#[serde(skip)]
	pub extended_data: Vec<Option<f32>>,

	/// Monthly estimates.
	#[serde(skip)]
	pub monthly_estimates: Vec<f32>,
}

impl From<System> for FullSystem {
	fn from(value: System) -> Self {
		Self {
			system: value,
			..Default::default()
		}
	}
}

/// System [tariff](https://www.energy.gov.au/solar/financial-benefits-solar/electricity-pricing-plans-and-tariffs)
/// information.
///
/// Part of a [`FullSystem`] response.
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct Tariffs {
	/// Export tariff in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub export: Option<f32>,

	/// Import peak tariff in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub import_peak: Option<f32>,

	/// Import off-peak tariff in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub import_off_peak: Option<f32>,

	/// Import shoulder tariff in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub import_shoulder: Option<f32>,

	/// Import high shoulder tariff in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub import_high_shoulder: Option<f32>,

	/// Daily import charge in cents.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub daily: Option<f32>,
}

/// Solar array panel orientation.
#[derive(Debug, Clone, Copy, Deserialize, Eq, PartialEq, Hash)]
pub enum Orientation {
	#[serde(rename = "N")]
	North,

	#[serde(rename = "NE")]
	NorthEast,

	#[serde(rename = "NW")]
	NorthWest,

	#[serde(rename = "W")]
	West,

	#[serde(rename = "E")]
	East,

	#[serde(rename = "EW")]
	EastWest,

	#[serde(rename = "S")]
	South,

	#[serde(rename = "SE")]
	SouthEast,

	#[serde(rename = "SW")]
	SouthWest,
}

/// Solar array shade level.
#[derive(Debug, Clone, Copy, Deserialize, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum Shade {
	/// No shade.
	No,

	/// Low shade.
	Low,

	/// Medium shade.
	Medium,

	/// High shade.
	High,
}

/// Ladder ranking information.
///
/// Returned by the [`get_ladder`](crate::Client::get_ladder) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Ladder {
	/// Ranking date.
	pub date: Date,

	/// Generation rank.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub generation_rank: Option<u32>,

	/// Efficiency rank.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub efficiency_rank: Option<u32>,

	/// Average efficiency in kilowatt-hours per kilowatt-hour.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub efficiency: Option<f32>,

	/// Total number of outputs in days.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub total_outputs: Option<u32>,

	/// Date of the latest output considered by the ranking.
	pub last_output: Option<Date>,

	/// Total generation in watt-hours.
	#[serde(deserialize_with = "opt_nan_u64")]
	pub total_generation: Option<u64>,

	/// Total consumption in watt-hours.
	#[serde(deserialize_with = "opt_nan_u64")]
	pub total_consumption: Option<u64>,

	/// Maximum generation in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub max_generation: Option<u32>,

	/// Maximum consumption in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub max_consumption: Option<u32>,

	/// Age of this system in days.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub system_age: Option<u32>,
}

impl Ladder {
	/// Returns a URL for this system's generation rank on PVOutput.org's `ladder.jsp` page.
	#[must_use]
	pub fn generation_rank_url(&self) -> Option<String> {
		self
			.generation_rank
			.map(|rank| format!("https://pvoutput.org/ladder.jsp?rank={rank}&o=e&d=desc&filter=0&p={}", rank / 30))
	}
}

/// A daily output.
///
/// Returned by the [`get_outputs`](crate::Client::get_outputs) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Output {
	pub date: Date,

	/// Energy generated in watt-hours.
	pub energy_generation: u32,

	/// Energy efficiency in kilowatt-hours per kilowatt-hour.
	pub energy_efficiency: f32,

	/// Energy exported in watt-hours.
	pub energy_exported: u32,

	/// Energy used in watt-hours.
	pub energy_used: u32,

	/// Peak power generation in watts.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub peak_power: Option<u32>,

	/// Peak power generation time.
	#[serde(deserialize_with = "opt_nan_time")]
	pub peak_time: Option<Time>,

	/// Weather conditions.
	pub conditions: Conditions,

	/// Minimum temperature in degrees Celsius.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub min_temperature: Option<u32>,

	/// Maximum temperature in degrees Celsius.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub max_temperature: Option<u32>,

	/// Peak energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub peak_energy_import: Option<u32>,

	/// Off-peak energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub off_peak_energy_import: Option<u32>,

	/// Shoulder energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub shoulder_energy_import: Option<u32>,

	/// High-shoulder energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub high_shoulder_energy_import: Option<u32>,

	#[serde(skip)]
	/// Export data.
	pub export: Option<OutputExport>,

	/// Insolation in watt-hours.
	#[serde(skip)]
	pub insolation: Option<u32>,
}

/// Energy export information for an [`Output`].
#[derive(Clone, Debug, Deserialize, Default)]
pub struct OutputExport {
	/// Peak energy export in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub peak_energy_export: Option<u32>,

	/// Off-peak energy export in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub off_peak_energy_export: Option<u32>,

	/// Shoulder energy export in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub shoulder_energy_export: Option<u32>,

	/// High-shoulder energy export in watt-hours.
	#[serde(deserialize_with = "opt_nan_u32")]
	pub high_shoulder_energy_export: Option<u32>,
}

/// Aggregated output data.
///
/// Returned by the [`get_aggregate_outputs`](crate::Client::get_aggregate_outputs) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct AggregatedOutput {
	/// The month or year of the aggregated output.
	pub date: AggregateDate,

	/// Number of outputs.
	pub outputs: u32,

	/// Energy generated in watt-hours.
	pub energy_generation: u64,

	/// Energy efficiency in kilowatt-hours per kilowatt-hour.
	pub energy_efficiency: f32,

	/// Energy exported in watt-hours.
	pub energy_exported: u64,

	/// Energy used in watt-hours.
	pub energy_used: u64,

	/// Peak energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub peak_energy_import: Option<f32>,

	/// Off-peak energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub off_peak_energy_import: Option<f32>,

	/// Shoulder energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub shoulder_energy_import: Option<f32>,

	/// High-shoulder energy import in watt-hours.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub high_shoulder_energy_import: Option<f32>,

	#[serde(skip)]
	/// Export data.
	pub export: Option<OutputExport>,
}

/// A date range for an [`AggregatedOutput`].
///
/// Represents either a year or a year and month.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AggregateDate {
	/// A year.
	Year(u16),

	/// A year and month.
	YearAndMonth(u16, u8),
}

impl<'de> Deserialize<'de> for AggregateDate {
	fn deserialize<D>(d: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		let s = String::deserialize(d)?;
		Ok(if s.len() == 4 {
			Self::Year(s.parse().map_err(Error::custom)?)
		} else {
			let (year, month) = s.split_at_checked(4).ok_or_else(|| Error::custom(format!("invalid date: {s}")))?;
			Self::YearAndMonth(year.parse().map_err(Error::custom)?, month.parse().map_err(Error::custom)?)
		})
	}
}

impl AggregateDate {
	/// Converts the [`AggregateDate`] to an arbitrary jiff [`Date`].
	/// - A `Year` will be converted to a `Date` on the first day of the first month of that year.
	/// - A `YearAndMonth` will be converted to a `Date` on the first day of that month of that year.
	///
	/// # Errors
	/// Will return an error if the [`AggregateDate`] is not a valid, jiff-expressible year or year and month.
	/// For example, `Year(10_000)` will return an error, as years in jiff must be below 9999.
	///
	/// # Example
	/// ```rust
	/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
	/// use pvoutput_client::types::response::AggregateDate;
	/// use jiff::civil::Date;
	///
	/// assert_eq!(AggregateDate::Year(2025).as_arbitrary_date()?, Date::constant(2025, 1, 1));
	/// assert_eq!(AggregateDate::YearAndMonth(2025, 9).as_arbitrary_date()?, Date::constant(2025, 9, 1));
	/// # Ok(())
	/// # }
	/// ```
	pub fn as_arbitrary_date(&self) -> Result<Date, jiff::Error> {
		#[allow(clippy::cast_possible_wrap)]
		match self {
			Self::Year(year) => Date::new(*year as i16, 1, 1),
			Self::YearAndMonth(year, month) => Date::new(*year as i16, *month as i8, 1),
		}
	}

	/// Returns this [`AggregateDate`]'s year.
	///
	/// # Example
	/// ```rust
	/// use pvoutput_client::types::response::AggregateDate;
	/// assert_eq!(AggregateDate::Year(2025).year(), 2025);
	/// assert_eq!(AggregateDate::YearAndMonth(2025, 9).year(), 2025);
	/// ```
	#[allow(clippy::must_use_candidate)]
	pub const fn year(&self) -> u16 {
		match self {
			Self::Year(year) | Self::YearAndMonth(year, _) => *year,
		}
	}
}

/// Daily team output data.
///
/// Returned by the [`get_team_outputs`](crate::Client::get_team_outputs) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct TeamOutput {
	/// The date this output corresponds to.
	pub date: Date,

	/// Number of outputs.
	pub outputs: u32,

	/// Energy efficiency in kilowatt-hours per kilowatt-hour.
	pub energy_efficiency: f32,

	/// Total energy generated in watt-hours.
	pub energy_generation: u32,

	/// Average energy generation in watt-hours.
	pub average_energy_generation: u32,

	/// Total energy exported in watt-hours.
	pub energy_exported: u32,

	/// Total energy consumed in watt-hours.
	pub energy_consumed: u32,

	/// Average energy consumption in watt-hours.
	pub average_energy_consumption: u32,

	/// Total energy imported in watt-hours.
	pub energy_imported: u32,
}

/// One day of user-defined [extended data](https://pvoutput.org/help/extended_data.html).
///
/// Returned by the [`get_extended`](crate::Client::get_extended) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct ExtendedData {
	/// The date for these data.
	pub date: Date,

	/// User-defined [extended data](https://pvoutput.org/help/extended_data.html) parameter 1.
	#[serde(default, deserialize_with = "opt_nan_f32")]
	pub extended_value_1: Option<f32>,

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

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

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

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

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

/// A favourite system.
///
/// Returned by the [`get_favourites`](crate::Client::get_favourites) endpoint.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct FavouriteSystem {
	/// System information.
	#[serde(skip)]
	pub system: System,

	/// System ID.
	pub id: u32,

	/// Status interval in minutes.
	pub status_interval: u32,
}

impl FavouriteSystem {
	#[must_use]
	pub(crate) const fn new(system: System, system_id: u32, status_interval: u32) -> Self {
		Self {
			system,
			id: system_id,
			status_interval,
		}
	}
}

/// Insolation data.
///
/// Returned by the [`get_insolation`](crate::Client::get_insolation) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Insolation {
	/// Time for the calculated insolation data.
	pub time: Time,

	/// Power in watts.
	pub power: u32,

	/// Energy in watt-hours.
	pub energy: u32,
}

/// A search result.
///
/// Returned by the [`search`](crate::Client::search) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct SearchResult {
	/// Name.
	pub name: String,

	/// Size in watts.
	pub size: u64,

	/// Postcode.
	pub postcode: String,

	/// Orientation.
	pub orientation: Orientation,

	/// Number of outputs.
	pub outputs: u32,

	/// How long ago the last output was recorded, or `None` if the system has no outputs.
	#[serde(deserialize_with = "search_span")]
	pub last_output: Option<Span>,

	/// System ID.
	pub system_id: u32,

	/// Panel brand.
	pub panel: Option<String>,

	/// Inverter brand.
	pub inverter: Option<String>,

	/// Distance in kilometres from the location provided in the search query.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub distance: Option<f32>,

	/// Latitude.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub latitude: Option<f32>,

	/// Longitude.
	#[serde(deserialize_with = "opt_nan_f32")]
	pub longitude: Option<f32>,
}

/// A [team](https://pvoutput.org/help/teams.html).
///
/// Returned by the [`get_team`](crate::Client::get_team) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Team {
	/// Team name.
	pub name: String,

	/// Team system size in watts.
	pub size: u64,

	/// Average system size in watts.
	pub average_size: u32,

	/// Number of systems in this team.
	pub systems: u32,

	/// Total energy generated in watt-hours.
	pub energy_generation: u64,

	/// Number of outputs recorded.
	pub outputs: u32,

	/// Average energy generation in watt-hours.
	pub average_energy_generation: u32,

	/// Type of team.
	pub team_type: TeamType,

	/// Team description.
	pub description: String,

	/// Team creation date.
	pub created: Date,
}

/// A category for a [`Team`].
#[derive(Debug, Clone, Deserialize)]
pub enum TeamType {
	/// A team for a particular panel brand.
	Panel,

	/// A team for a particular inverter brand.
	Inverter,

	/// A team for a geographic region or location.
	Geographic,

	/// A team for a particular installer.
	Installer,

	/// A team for a specific piece of software.
	Software,

	/// A general team.
	General,
}

/// Supply and demand information for a particular region.
///
/// Returned by the [`get_supply`](crate::Client::get_supply) endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct Supply {
	/// Timestamp for the aggregated data.
	pub timestamp: Timestamp,

	/// The region these data are for.
	pub region: Region,

	/// Utilisation as a percentage.
	pub utilisation: f32,

	/// Total power output in watts.
	pub power_output: u64,

	/// Total power input in watts.
	pub power_input: u64,

	/// Average power output in watts.
	pub average_power_output: u32,

	/// Average power input in watts.
	pub average_power_input: u32,

	/// Average net power in watts.
	pub average_net_power: i32,

	/// Systems outputting power(?).
	pub systems_out: u32,

	/// Systems consuming power(?).
	pub systems_in: u32,

	/// Total size of this region's systems in watts.
	pub total_size: u64,

	/// Average size of this region's systems in watts.
	#[serde(deserialize_with = "opt_negative_u32")]
	pub average_size: Option<u32>,
}

/// Status information for a status uploaded to a batch status endpoint.
///
/// Returned by the [`crate::Client::add_batch_status`] and [`crate::Client::add_batch_status_net`] endpoints.
#[derive(Clone, Debug, Deserialize)]
pub struct BatchStatusReport {
	/// The date for this status.
	pub date: Date,

	/// The time for this status.
	pub time: Time,

	/// Whether this status was successful.
	#[serde(deserialize_with = "bool_int")]
	pub success: bool,
}

// custom deserialiser functions

/// Deserialises an `f32`, treating `NaN` as `None`.
pub(crate) fn opt_nan_f32<'de, D>(d: D) -> Result<Option<f32>, D::Error>
where
	D: Deserializer<'de>,
{
	Option::<f32>::deserialize(d).map(|r| r.filter(|f| !f.is_nan()))
}

/// Deserialises a `u32`, treating `NaN` as `None`.
pub(crate) fn opt_nan_u32<'de, D>(d: D) -> Result<Option<u32>, D::Error>
where
	D: Deserializer<'de>,
{
	#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
	Option::<f32>::deserialize(d).map(|r| r.filter(|f| !f.is_nan()).map(|f| f as u32))
}

/// Deserialises a `u64`, treating `NaN` as `None`.
pub(crate) fn opt_nan_u64<'de, D>(d: D) -> Result<Option<u64>, D::Error>
where
	D: Deserializer<'de>,
{
	#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
	Option::<f64>::deserialize(d).map(|r| r.filter(|f| !f.is_nan()).map(|f| f as u64))
}

/// Deserialises a `Time`, treating `NaN` as `None`.
pub(crate) fn opt_nan_time<'de, D>(d: D) -> Result<Option<Time>, D::Error>
where
	D: Deserializer<'de>,
{
	match String::deserialize(d)?.as_str() {
		"NaN" => Ok(None),
		s => Ok(Some(s.parse().map_err(Error::custom)?)),
	}
}

/// Deserialises a `u32`, treating `-1` as `None`.
pub(crate) fn opt_negative_u32<'de, D>(d: D) -> Result<Option<u32>, D::Error>
where
	D: Deserializer<'de>,
{
	#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
	match i64::deserialize(d)? {
		-1 => Ok(None),
		n => Ok(Some(u32::try_from(n).map_err(Error::custom)?)),
	}
}

/// Deserialises a nullable value, treating `null` as `None`.
fn nullable<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
where
	D: Deserializer<'de>,
	T: DeserializeOwned,
{
	// h/t https://stackoverflow.com/a/56384732
	#[derive(Deserialize)]
	#[serde(untagged)]
	enum Maybe<T> {
		Some(Option<T>),
		OtherString(String),
	}

	match Deserialize::deserialize(d)? {
		Maybe::Some(s) => Ok(s),
		Maybe::OtherString(s) if s == "null" => Ok(None),
		Maybe::OtherString(s) => Err(Error::custom(format!("invalid value: {s}"))),
	}
}

/// Parses the following:
/// - No Output -> `None`
/// - Today -> `Span::new()`
/// - Yesterday -> `Span::new().days(1)`
/// - n days ago -> `Span::new().days(n)`
/// - n weeks ago -> `Span::new().weeks(n)`
fn search_span<'de, D>(d: D) -> Result<Option<Span>, D::Error>
where
	D: Deserializer<'de>,
{
	Ok(match String::deserialize(d)?.as_str() {
		"No Outputs" => None,
		"Today" => Some(Span::new()),
		"Yesterday" => Some(Span::new().days(1)),
		days if days.ends_with("days ago") => {
			Some(Span::new().days(days.split(' ').next().unwrap().parse::<i64>().map_err(Error::custom)?))
		}
		weeks if weeks.ends_with("weeks ago") || weeks.ends_with("week ago") => {
			Some(Span::new().weeks(weeks.split(' ').next().unwrap().parse::<i64>().map_err(Error::custom)?))
		}
		other => return Err(Error::custom(format!("Couldn't parse {other} as Span!"))),
	})
}

/// Deserialises a boolean from an integer.
fn bool_int<'de, D>(d: D) -> Result<bool, D::Error>
where
	D: Deserializer<'de>,
{
	Ok(match u8::deserialize(d)? {
		0 => false,
		1 => true,
		_ => return Err(Error::custom("invalid value")),
	})
}