File: types.py

package info (click to toggle)
zabbix-cli 3.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,980 kB
  • sloc: python: 19,920; makefile: 5
file content (1308 lines) | stat: -rw-r--r-- 40,861 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
"""Type definitions for Zabbix API objects.

Since we are supporting multiple versions of the Zabbix API at the same time,
we don't operate with very strict type definitions. Some definitions are
TypedDicts, while others are Pydantic models. All models are able to
take extra fields, since we don't know (or always care) which fields are
present in which API versions.

It's not type-safe, but it's better than nothing. In the future, we might
want to look into defining Pydantic models that can accommodate multiple
Zabbix versions.
"""

from __future__ import annotations

import logging
from collections.abc import Iterable
from collections.abc import MutableMapping
from collections.abc import Sequence
from datetime import datetime
from datetime import timedelta
from typing import Annotated
from typing import Any
from typing import Optional
from typing import Union

from pydantic import AliasChoices
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from pydantic import FieldSerializationInfo
from pydantic import PlainSerializer
from pydantic import SerializationInfo
from pydantic import ValidationError
from pydantic import ValidationInfo
from pydantic import ValidatorFunctionWrapHandler
from pydantic import WrapValidator
from pydantic import computed_field
from pydantic import field_serializer
from pydantic import field_validator
from pydantic_core import PydanticCustomError
from typing_extensions import Literal
from typing_extensions import TypeAliasType
from typing_extensions import TypedDict

from zabbix_cli.models import ColsRowsType
from zabbix_cli.models import RowsType
from zabbix_cli.models import TableRenderable
from zabbix_cli.output.style import Color
from zabbix_cli.pyzabbix.enums import AckStatus
from zabbix_cli.pyzabbix.enums import ActiveInterface
from zabbix_cli.pyzabbix.enums import EventStatus
from zabbix_cli.pyzabbix.enums import GUIAccess
from zabbix_cli.pyzabbix.enums import HostgroupFlag
from zabbix_cli.pyzabbix.enums import HostgroupType
from zabbix_cli.pyzabbix.enums import InterfaceConnectionMode
from zabbix_cli.pyzabbix.enums import InterfaceType
from zabbix_cli.pyzabbix.enums import ItemType
from zabbix_cli.pyzabbix.enums import MacroType
from zabbix_cli.pyzabbix.enums import MaintenancePeriodType
from zabbix_cli.pyzabbix.enums import MaintenanceStatus
from zabbix_cli.pyzabbix.enums import MaintenanceWeekType
from zabbix_cli.pyzabbix.enums import MediaTypeType
from zabbix_cli.pyzabbix.enums import MonitoredBy
from zabbix_cli.pyzabbix.enums import MonitoringStatus
from zabbix_cli.pyzabbix.enums import ProxyCompatibility
from zabbix_cli.pyzabbix.enums import ProxyGroupState
from zabbix_cli.pyzabbix.enums import ProxyMode
from zabbix_cli.pyzabbix.enums import ProxyModePre70
from zabbix_cli.pyzabbix.enums import TriggerPriority
from zabbix_cli.pyzabbix.enums import UsergroupPermission
from zabbix_cli.pyzabbix.enums import UsergroupStatus
from zabbix_cli.pyzabbix.enums import UserRole
from zabbix_cli.pyzabbix.enums import ValueType
from zabbix_cli.utils.utils import get_maintenance_active_days
from zabbix_cli.utils.utils import get_maintenance_active_months
from zabbix_cli.utils.utils import get_maintenance_status
from zabbix_cli.utils.utils import get_monitoring_status

logger = logging.getLogger(__name__)

SortOrder = Literal["ASC", "DESC"]


# Source: https://docs.pydantic.dev/2.7/concepts/types/#named-recursive-types
def json_custom_error_validator(
    value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo
) -> Any:
    """Simplify the error message to avoid a gross error stemming from
    exhaustive checking of all union options.
    """  # noqa: D205
    try:
        return handler(value)
    except ValidationError:
        raise PydanticCustomError(
            "invalid_json",
            "Input is not valid json",
        ) from None


Json = TypeAliasType(
    "Json",
    Annotated[
        Union[
            MutableMapping[str, "Json"],
            Sequence["Json"],
            str,
            int,
            float,
            bool,
            None,
        ],
        WrapValidator(json_custom_error_validator),
    ],
)


ParamsType = MutableMapping[str, Json]
"""Type used to construct parameters for API requests.
Can only contain native JSON-serializable types.

BaseModel objects must be converted to JSON-serializable dicts before being
assigned as values in a ParamsType.
"""


def serialize_host_list_json(
    hosts: list[Host], info: SerializationInfo
) -> list[dict[str, str]]:
    """Custom JSON serializer for a list of hosts.

    Most of the time we don't want to serialize _all_ fields of a host.
    This serializer assumes that we want to serialize the minimal representation
    of hosts unless the context specifies otherwise.
    """
    if isinstance(info.context, dict):
        if info.context.get("full_host"):  # pyright: ignore[reportUnknownMemberType]
            return [host.model_dump(mode="json") for host in hosts]
    return [host.model_simple_dump() for host in hosts]


HostList = Annotated[
    list["Host"], PlainSerializer(serialize_host_list_json, when_used="json")
]
"""List of hosts that serialize as the minimal representation of a list of hosts."""


def age_from_datetime(dt: Optional[datetime]) -> Optional[str]:
    """Returns the age of a datetime object as a human-readable
    string, or None if the datetime is None.
    """
    if not dt:
        return None
    n = datetime.now(tz=dt.tzinfo)
    age = n - dt
    # strip microseconds
    return str(age - timedelta(microseconds=age.microseconds))


def format_datetime(dt: Optional[datetime]) -> str:
    """Returns a formatted datetime string, or empty string if the
    datetime is None.
    """
    if not dt:
        return ""
    return dt.strftime("%Y-%m-%d %H:%M:%S")


class ModifyHostItem(TypedDict):
    """Argument for a host ID in an API request."""

    hostid: Union[str, int]


ModifyHostParams = list[ModifyHostItem]

"""A list of host IDs in an API request.

E.g. `[{"hostid": "123"}, {"hostid": "456"}]`
"""


class ModifyGroupItem(TypedDict):
    """Argument for a group ID in an API request."""

    groupid: Union[str, int]


ModifyGroupParams = list[ModifyGroupItem]
"""A list of host/template group IDs in an API request.

E.g. `[{"groupid": "123"}, {"groupid": "456"}]`
"""


class ModifyTemplateItem(TypedDict):
    """Argument for a template ID in an API request."""

    templateid: Union[str, int]


ModifyTemplateParams = list[ModifyTemplateItem]
"""A list of template IDs in an API request.

E.g. `[{"templateid": "123"}, {"templateid": "456"}]`
"""


class ZabbixAPIError(BaseModel):
    """Zabbix API error information."""

    code: int
    message: str
    data: Optional[str] = None


class ZabbixAPIResponse(BaseModel):
    """The raw response from the Zabbix API"""

    jsonrpc: str
    id: int
    result: Any = None  # can subclass this and specify types (ie. ZabbixAPIListResponse, ZabbixAPIStrResponse, etc.)
    """Result of API call, if request succeeded."""
    error: Optional[ZabbixAPIError] = None
    """Error info, if request failed."""


class ZabbixAPIBaseModel(TableRenderable):
    """Base model for Zabbix API objects.

    Implements the `TableRenderable` interface, which allows us to render
    it as a table, JSON, csv, etc.
    """

    model_config = ConfigDict(validate_assignment=True, extra="ignore")

    def model_dump_api(self) -> dict[str, Any]:
        """Dump the model as a JSON-serializable dict used in API calls.

        Excludes computed fields by default.
        """
        return self.model_dump(
            mode="json",
            exclude=set(self.model_computed_fields),
            exclude_none=True,
        )


class ZabbixRight(ZabbixAPIBaseModel):
    permission: int
    id: str
    name: Optional[str] = None  # name of group (injected by application)

    @computed_field
    @property
    def permission_str(self) -> str:
        """Returns the permission as a formatted string."""
        return UsergroupPermission.string_from_value(self.permission)

    def model_dump_api(self) -> dict[str, Any]:
        return self.model_dump(
            mode="json", include={"permission", "id"}, exclude_none=True
        )


class User(ZabbixAPIBaseModel):
    userid: str
    username: str = Field(..., validation_alias=AliasChoices("username", "alias"))
    name: Optional[str] = None
    surname: Optional[str] = None
    url: Optional[str] = None
    autologin: Optional[str] = None
    autologout: Optional[str] = None
    roleid: Optional[int] = Field(
        default=None, validation_alias=AliasChoices("roleid", "type")
    )
    # NOTE: Not adding properties we don't use, since Zabbix has a habit of breaking
    # its own API by changing names and types of properties between versions.

    @computed_field
    @property
    def role(self) -> Optional[str]:
        """Returns the role name, if available."""
        if self.roleid:
            return UserRole.string_from_value(self.roleid)
        return None

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["UserID", "Username", "Name", "Surname", "Role"]
        rows: RowsType = [
            [
                self.userid,
                self.username,
                self.name or "",
                self.surname or "",
                self.role or "",
            ]
        ]
        return cols, rows


class Usergroup(ZabbixAPIBaseModel):
    name: str
    usrgrpid: str
    gui_access: int
    users_status: int
    rights: list[ZabbixRight] = []
    hostgroup_rights: list[ZabbixRight] = []
    templategroup_rights: list[ZabbixRight] = []
    users: list[User] = []

    @computed_field
    @property
    def gui_access_str(self) -> str:
        """GUI access code as a formatted string."""
        return GUIAccess.string_from_value(self.gui_access)

    @computed_field
    @property
    def users_status_str(self) -> str:
        """User status as a formatted string."""
        return UsergroupStatus.string_from_value(self.users_status)

    # LEGACY
    @computed_field
    @property
    def status(self) -> str:
        """LEGACY: 'users_status' is called 'status' in V2.
        Ensures serialized output contains the field.
        """
        return UsergroupStatus.string_from_value(self.users_status, with_code=True)

    # LEGACY
    @field_serializer("gui_access")
    def _LEGACY_type_serializer(
        self, v: Optional[int], _info: FieldSerializationInfo
    ) -> Union[str, int, None]:
        """Serializes the GUI access status as a formatted string in legacy JSON mode"""
        if self.legacy_json_format:
            return GUIAccess.string_from_value(v, with_code=True)
        return v


class Template(ZabbixAPIBaseModel):
    """A template object. Can contain hosts and other templates."""

    templateid: str
    host: str
    hosts: HostList = []
    macros: list[Macro] = []

    templates: list[Template] = []
    """Child templates (templates inherited from this template)."""

    parent_templates: list[Template] = Field(
        default_factory=list,
        validation_alias=AliasChoices("parentTemplates", "parent_templates"),
        serialization_alias="parentTemplates",  # match JSON output to API format
    )
    """Parent templates (templates this template inherits from)."""

    name: Optional[str] = None
    """The visible name of the template."""

    def __str__(self) -> str:
        return f"{self.name or self.host!r} ({self.templateid})"

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["ID", "Name", "Hosts", "Parents", "Children"]
        rows: RowsType = [
            [
                self.templateid,
                self.name or self.host,  # prefer name, fall back on host
                "\n".join([host.host for host in self.hosts]),
                "\n".join([parent.host for parent in self.parent_templates]),
                "\n".join([template.host for template in self.templates]),
            ]
        ]
        return cols, rows


class TemplateGroup(ZabbixAPIBaseModel):
    groupid: str
    name: str
    uuid: str
    templates: list[Template] = []


class HostGroup(ZabbixAPIBaseModel):
    groupid: str
    name: str
    hosts: HostList = []
    flags: int = 0
    internal: Optional[int] = None  # <6.2
    templates: list[Template] = []  # <6.2

    def __cols_rows__(self) -> ColsRowsType:
        # FIXME: is this ever used? Can we remove?
        cols = ["GroupID", "Name", "Flag", "Type", "Hosts"]
        rows: RowsType = [
            [
                self.groupid,
                self.name,
                HostgroupFlag.string_from_value(self.flags),
                HostgroupType.string_from_value(self.internal),
                ", ".join([host.host for host in self.hosts]),
            ]
        ]
        return cols, rows


class DictModel(ZabbixAPIBaseModel):
    """An adapter for a dict that allows it to be rendered as a table."""

    model_config = ConfigDict(extra="allow")

    def items(self) -> Iterable[tuple[str, Any]]:
        return self.model_dump(mode="python").items()

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["Key", "Value"]
        rows: RowsType = [[key, str(value)] for key, value in self.items() if value]
        return cols, rows


# TODO: expand Host model with all possible fields
# Add alternative constructor to construct from API result
class Host(ZabbixAPIBaseModel):
    hostid: str
    host: str = ""
    description: Optional[str] = None
    groups: list[HostGroup] = Field(
        default_factory=list,
        # Compat for >= 6.2.0
        validation_alias=AliasChoices("groups", "hostgroups"),
    )
    templates: list[Template] = Field(
        default_factory=list,
        validation_alias=AliasChoices("templates", "parentTemplates"),
    )
    inventory: DictModel = Field(default_factory=DictModel)
    monitored_by: Optional[MonitoredBy] = None
    proxyid: Optional[str] = Field(
        default=None,
        # Compat for <7.0.0
        validation_alias=AliasChoices("proxyid", "proxy_hostid"),
    )
    proxy_groupid: Optional[str] = None  # >= 7.0
    maintenance_status: Optional[str] = None
    # active_available is a new field in 7.0.
    # Previous versions required checking the `available` field of its first interface.
    # In zabbix-cli v2, this value was serialized as `zabbix_agent`.
    active_available: Optional[str] = Field(
        default=None,
        validation_alias=AliasChoices(
            "active_available",  # >= 7.0
            "zabbix_agent",  # Zabbix-cli V2 name of this field
        ),
    )
    status: Optional[str] = None
    macros: list[Macro] = Field(default_factory=list)
    interfaces: list[HostInterface] = Field(default_factory=list)

    # HACK: Add a field for the host's proxy that we can inject later
    proxy: Optional[Proxy] = None

    def __str__(self) -> str:
        return f"{self.host!r} ({self.hostid})"

    def model_simple_dump(self) -> dict[str, str]:
        """Dump the model with minimal fields for simple output."""
        return {
            "host": self.host,
            "hostid": self.hostid,
        }

    def set_proxy(self, proxy_map: dict[str, Proxy]) -> None:
        """Set proxy info for the host given a mapping of proxy IDs to proxies."""
        if not (proxy := proxy_map.get(str(self.proxyid))):
            return
        self.proxy = proxy

    def get_active_status(self, *, with_code: bool = False) -> str:
        """Returns the active interface status as a formatted string."""
        if self.zabbix_version.release >= (7, 0, 0):
            return ActiveInterface.string_from_value(
                self.active_available, with_code=with_code
            )
        # We are on pre-7.0.0, check the first interface
        iface = self.interfaces[0] if self.interfaces else None
        if iface:
            return ActiveInterface.string_from_value(
                iface.available, with_code=with_code
            )
        else:
            return ActiveInterface.UNKNOWN.as_status(with_code=with_code)

    # Legacy V2 JSON format compatibility
    @field_serializer("maintenance_status", when_used="json")
    def _LEGACY_maintenance_status_serializer(
        self, v: Optional[str], _info: FieldSerializationInfo
    ) -> Optional[str]:
        """Serializes the maintenance status as a formatted string
        in legacy mode, and as-is in new mode.
        """
        if self.legacy_json_format:
            return get_maintenance_status(v, with_code=True)
        return v

    @computed_field
    @property
    def zabbix_agent(self) -> str:
        """LEGACY: Serializes the zabbix agent status as a formatted string
        in legacy mode, and as-is in new mode.
        """
        # NOTE: use `self.active_available` instead of `self.zabbix_agent`
        if self.legacy_json_format:
            return self.get_active_status(with_code=True)
        return self.get_active_status()

    @field_serializer("status", when_used="json")
    def _LEGACY_status_serializer(
        self, v: Optional[str], _info: FieldSerializationInfo
    ) -> Optional[str]:
        """Serializes the monitoring status as a formatted string
        in legacy mode, and as-is in new mode.
        """
        if self.legacy_json_format:
            return get_monitoring_status(v, with_code=True)
        return v

    @field_validator("host", mode="before")  # TODO: add test for this
    @classmethod
    def _use_id_if_empty(cls, v: str, info: ValidationInfo) -> str:
        """In case the Zabbix API returns no host name, use the ID instead."""
        if not v:
            return f"Unknown (ID: {info.data.get('hostid')})"
        return v

    @field_validator("proxyid", mode="after")  # TODO: add test for this
    @classmethod
    def _proxyid_0_is_none(cls, v: str, info: ValidationInfo) -> Optional[str]:
        """Zabbix API can return 0 if host has no proxy.

        Convert to None, so we know the proxyid can always be used to
        look up the proxy, as well as in boolean contexts.
        """
        if not v or v == "0":
            return None
        return v

    def __cols_rows__(self) -> ColsRowsType:
        cols = [
            "HostID",
            "Name",
            "Host groups",
            "Templates",
            "Agent",
            "Maintenance",
            "Status",
            "Proxy",
        ]
        rows: RowsType = [
            [
                self.hostid,
                self.host,
                "\n".join([group.name for group in self.groups]),
                "\n".join([template.host for template in self.templates]),
                self.zabbix_agent,
                MaintenanceStatus.string_from_value(self.maintenance_status),
                MonitoringStatus.string_from_value(self.status),
                self.proxy.name if self.proxy else "",
            ]
        ]
        return cols, rows


class HostInterface(ZabbixAPIBaseModel):
    type: int
    ip: str
    dns: Optional[str] = None
    port: str
    useip: int
    main: int
    # Values not required for creation:
    interfaceid: Optional[str] = None
    available: Optional[int] = None
    hostid: Optional[str] = None
    bulk: Optional[int] = None

    @computed_field
    @property
    def connection_mode(self) -> str:
        """Returns the connection mode as a formatted string."""
        return InterfaceConnectionMode.string_from_value(self.useip)

    @computed_field
    @property
    def type_str(self) -> str:
        """Returns the interface type as a formatted string."""
        return InterfaceType.string_from_value(self.type)

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["ID", "Type", "IP", "DNS", "Port", "Mode", "Default", "Available"]
        rows: RowsType = [
            [
                self.interfaceid or "",
                str(InterfaceType(self.type).value),
                self.ip,
                self.dns or "",
                self.port,
                self.connection_mode,
                str(bool(self.main)),
                ActiveInterface.string_from_value(self.available),
            ]
        ]
        return cols, rows


class CreateHostInterfaceDetails(ZabbixAPIBaseModel):
    """Parameters for creating a host interface."""

    version: int
    bulk: Optional[int] = None
    community: Optional[str] = None
    max_repetitions: Optional[int] = None
    securityname: Optional[str] = None
    securitylevel: Optional[int] = None
    authpassphrase: Optional[str] = None
    privpassphrase: Optional[str] = None
    authprotocol: Optional[int] = None
    privprotocol: Optional[int] = None
    contextname: Optional[str] = None


class UpdateHostInterfaceDetails(ZabbixAPIBaseModel):
    """Parameters for updating a host interface."""

    version: Optional[int] = None
    bulk: Optional[int] = None
    community: Optional[str] = None
    max_repetitions: Optional[int] = None
    securityname: Optional[str] = None
    securitylevel: Optional[int] = None
    authpassphrase: Optional[str] = None
    privpassphrase: Optional[str] = None
    authprotocol: Optional[int] = None
    privprotocol: Optional[int] = None
    contextname: Optional[str] = None


class Proxy(ZabbixAPIBaseModel):
    """Zabbix Proxy object."""

    proxyid: str
    name: str = Field(..., validation_alias=AliasChoices("host", "name"))
    hosts: HostList = Field(default_factory=list)
    status: Optional[int] = None
    operating_mode: Optional[int] = None
    address: str = Field(
        validation_alias=AliasChoices(
            "address",  # >=7.0.0
            "proxy_address",  # <7.0.0
        )
    )
    proxy_groupid: Optional[str] = None  # >= 7.0
    compatibility: Optional[int] = None  # >= 7.0
    version: Optional[int] = None  # >= 7.0
    local_address: Optional[str] = None  # >= 7.0
    local_port: Optional[str] = None  # >= 7.0

    def __hash__(self) -> str:
        return self.proxyid  # kinda hacky, but lets us use it in dicts

    @computed_field
    @property
    def mode(self) -> str:
        """Returns the proxy mode as a formatted string."""
        if self.zabbix_version.release >= (7, 0, 0):
            cls = ProxyMode
        else:
            cls = ProxyModePre70
        return cls.string_from_value(self.operating_mode)

    @computed_field
    @property
    def compatibility_str(self) -> str:
        """Returns the proxy compatibility as a formatted string."""
        return ProxyCompatibility.string_from_value(self.compatibility)

    @property
    def compatibility_rich(self) -> str:
        """Returns the proxy compatibility as a Rich markup formatted string."""
        compat = self.compatibility_str
        if compat == "Current":
            style = Color.SUCCESS
        elif compat == "Outdated":
            style = Color.WARNING
        elif compat == "Unsupported":
            style = Color.ERROR
        else:
            style = Color.INFO
        return style(compat)


class ProxyGroup(ZabbixAPIBaseModel):
    """Zabbix Proxy Group object."""

    proxy_groupid: str
    name: str
    description: str
    failover_delay: str
    min_online: str  # 1-1000, may be a macro
    state: ProxyGroupState
    proxies: list[Proxy] = Field(default_factory=list)

    def __cols_rows__(self) -> ColsRowsType:
        cols = [
            "ID",
            "Name",
            "Description",
            "Failover Delay",
            "Minimum Available",
            "State",
            "Proxies",
        ]
        rows: RowsType = [
            [
                self.proxy_groupid,
                self.name,
                self.description,
                self.failover_delay,
                str(self.min_online),
                str(self.state),  # TODO: make prettier
                "\n".join(proxy.name for proxy in self.proxies),
            ]
        ]
        return cols, rows


class MacroBase(ZabbixAPIBaseModel):
    macro: str
    value: Optional[str] = None  # Optional in case secret value
    type: int
    """Macro type. 0 - text, 1 - secret, 2 - vault secret (>=7.0)"""
    description: str

    @computed_field
    @property
    def type_str(self) -> str:
        """Returns the macro type as a formatted string."""
        return MacroType.string_from_value(self.type)


class Macro(MacroBase):
    """Macro object. Known as 'host macro' in the Zabbix API."""

    hostid: str
    hostmacroid: str
    automatic: Optional[int] = None  # >= 7.0 only. 0 = user, 1 = discovery rule
    hosts: HostList = Field(default_factory=list)
    templates: list[Template] = Field(default_factory=list)


class GlobalMacro(MacroBase):
    """Global macro object."""

    globalmacroid: str


class Item(ZabbixAPIBaseModel):
    """Zabbix Item."""

    itemid: str
    delay: Optional[str] = None
    hostid: Optional[str] = None
    interfaceid: Optional[str] = None
    key: Optional[str] = Field(
        default=None, validation_alias=AliasChoices("key_", "key")
    )
    name: Optional[str] = None
    type: Optional[int] = None
    url: Optional[str] = None
    value_type: Optional[int] = None
    description: Optional[str] = None
    history: Optional[str] = None
    lastvalue: Optional[str] = None
    hosts: HostList = []

    @computed_field
    @property
    def type_str(self) -> str:
        """Returns the item type as a formatted string."""
        return ItemType.string_from_value(self.type)

    @computed_field
    @property
    def value_type_str(self) -> str:
        """Returns the item type as a formatted string."""
        return ValueType.string_from_value(self.value_type)

    @field_serializer("type")
    def _LEGACY_type_serializer(
        self, v: Optional[int], _info: FieldSerializationInfo
    ) -> Union[str, int, None]:
        """Serializes the item type as a formatted string in legacy JSON mode."""
        if self.legacy_json_format:
            return self.type_str
        return v

    @field_serializer("value_type")
    def _LEGACY_value_type_serializer(
        self, v: Optional[int], _info: FieldSerializationInfo
    ) -> Union[str, int, None]:
        """Serializes the item type as a formatted string in legacy JSON mode."""
        if self.legacy_json_format:
            return self.type_str
        return v

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["ID", "Name", "Key", "Type", "Interval", "History", "Description"]
        rows: RowsType = [
            [
                self.itemid,
                str(self.name),
                str(self.key),
                str(self.type_str),
                str(self.delay),
                str(self.history),
                str(self.description),
            ]
        ]
        return cols, rows


class Role(ZabbixAPIBaseModel):
    roleid: str
    name: str
    type: int
    readonly: int  # 0 = read-write, 1 = read-only


class MediaType(ZabbixAPIBaseModel):
    mediatypeid: str
    name: str
    type: int
    description: Optional[str] = None

    @computed_field
    @property
    def type_str(self) -> str:
        return MediaTypeType.string_from_value(self.type)

    def __cols_rows__(self) -> ColsRowsType:
        cols = ["ID", "Name", "Type", "Description"]
        rows: RowsType = [
            [
                self.mediatypeid,
                self.name,
                self.type_str,
                self.description or "",
            ]
        ]
        return cols, rows


class UserMedia(ZabbixAPIBaseModel):
    """Media attached to a user object."""

    # https://www.zabbix.com/documentation/current/en/manual/api/reference/user/object#media
    mediatypeid: str
    sendto: str
    active: int = 0  # 0 = enabled, 1 = disabled (YES REALLY!)
    severity: int = 63  # all (1111 in binary - all bits set)
    period: str = "1-7,00:00-24:00"  # 24/7


class TimePeriod(ZabbixAPIBaseModel):
    period: int
    timeperiod_type: int
    start_date: Optional[datetime] = None
    start_time: Optional[int] = None
    every: Optional[int] = None
    dayofweek: Optional[int] = None
    day: Optional[int] = None
    month: Optional[int] = None

    @computed_field
    @property
    def timeperiod_type_str(self) -> str:
        """Returns the time period type as a formatted string."""
        return MaintenancePeriodType.string_from_value(self.timeperiod_type)

    @computed_field
    @property
    def period_str(self) -> str:
        return str(timedelta(seconds=self.period))

    @computed_field
    @property
    def start_time_str(self) -> str:
        return str(timedelta(seconds=self.start_time or 0))

    @computed_field
    @property
    def start_date_str(self) -> str:
        if self.start_date and self.start_date.year > 1970:  # hack to avoid 1970-01-01
            return self.start_date.strftime("%Y-%m-%d %H:%M")
        return ""

    @computed_field
    @property
    def month_str(self) -> list[str]:
        return get_maintenance_active_months(self.month)

    @computed_field
    @property
    def dayofweek_str(self) -> list[str]:
        return get_maintenance_active_days(self.dayofweek)

    @computed_field
    @property
    def every_str(self) -> str:
        return MaintenanceWeekType.string_from_value(self.every)

    def __cols_rows__(self) -> ColsRowsType:
        """Renders the table based on the time period type.

        Fields are added/removed based on the time period type.
        """
        # TODO: use MaintenancePeriodType enum for this
        if self.timeperiod_type == 0:
            return self._get_cols_rows_one_time()
        # TODO: add __cols_rows__ method for each timeperiod type
        # other timeperiod types here...
        else:
            return self._get_cols_rows_default()

    def _get_cols_rows_default(self) -> ColsRowsType:
        """Fallback for when we don't know the time period type."""
        cols = [
            "Type",
            "Duration",
            "Start date",
            "Start time",
            "Every",
            "Day of week",
            "Day",
            "Months",
        ]
        rows: RowsType = [
            [
                self.timeperiod_type_str,
                self.period_str,
                self.start_date_str,
                self.start_time_str,
                self.every_str,
                "\n".join(self.dayofweek_str),
                str(self.day),
                "\n".join(self.month_str),
            ]
        ]
        return cols, rows

    def _get_cols_rows_one_time(self) -> ColsRowsType:
        """Get the cols and rows for a one time schedule."""
        cols = ["Type", "Duration", "Start date"]
        rows: RowsType = [
            [
                self.timeperiod_type_str,
                self.period_str,
                self.start_date_str,
            ]
        ]
        return cols, rows


class ProblemTag(ZabbixAPIBaseModel):
    tag: str
    operator: Optional[int]
    value: Optional[str]


class Maintenance(ZabbixAPIBaseModel):
    maintenanceid: str
    name: str
    active_since: Optional[datetime] = None
    active_till: Optional[datetime] = None
    description: Optional[str] = None
    maintenance_type: Optional[int] = None
    tags_evaltype: Optional[int] = None
    timeperiods: list[TimePeriod] = []
    tags: list[ProblemTag] = []
    hosts: HostList = []
    hostgroups: list[HostGroup] = Field(
        default_factory=list, validation_alias=AliasChoices("groups", "hostgroups")
    )

    @field_validator("timeperiods", mode="after")
    @classmethod
    def _sort_time_periods(cls, v: list[TimePeriod]) -> list[TimePeriod]:
        """Cheeky hack to consistently render mixed time period types.

        This validator ensures time periods are sorted by complexity, so that the
        most complex ones are rendered first, thus adding all the necessary
        columns to the table when multiple time periods are rendered in aggregate.

        See: TimePeriod.__cols_rows__
        See: AggregateResult.__cols_rows__

        """
        # 0 = one time. We want those last.
        return sorted(v, key=lambda tp: tp.timeperiod_type, reverse=True)


class Event(ZabbixAPIBaseModel):
    eventid: str
    source: int
    object: int
    objectid: str
    acknowledged: int
    clock: Optional[datetime] = None
    name: str
    value: Optional[int] = None  # docs seem to imply this is optional
    severity: int
    # NYI:
    # r_eventid
    # c_eventid
    # cause_eventid
    # correlationid
    # userid
    # suppressed
    # opdata
    # urls

    @computed_field
    @property
    def age(self) -> Optional[str]:
        """Returns the age of the event as a formatted string."""
        return age_from_datetime(self.clock)

    @computed_field
    @property
    def status_str(self) -> str:
        return EventStatus.string_from_value(self.value)

    @computed_field
    @property
    def acknowledged_str(self) -> str:
        return AckStatus.string_from_value(self.acknowledged)

    @property
    def status_str_cell(self) -> str:
        """Formatted and styled status string for use in a table cell."""
        if self.status_str == "OK":
            color = "green"
        else:
            color = "red"
        return f"[{color}]{self.status_str}[/]"

    @property
    def acknowledged_str_cell(self) -> str:
        """Formatted and styled state string for use in a table cell."""
        if self.acknowledged_str == "Yes":
            color = "green"
        else:
            color = "red"
        return f"[{color}]{self.acknowledged_str}[/]"

    @field_serializer("value")
    def _LEGACY_value_serializer(
        self, v: Optional[int], _info: FieldSerializationInfo
    ) -> Union[str, int, None]:
        """Serializes the value field as a formatted string in legacy JSON mode"""
        if self.legacy_json_format:
            return self.status_str
        return v

    @field_serializer("acknowledged")
    def _LEGACY_acknowledged_serializer(
        self, v: int, _info: FieldSerializationInfo
    ) -> Union[str, int]:
        """Serializes the acknowledged field as a formatted string in legacy JSON mode"""
        if self.legacy_json_format:
            return self.acknowledged_str
        return v

    def __cols_rows__(self) -> ColsRowsType:
        cols = [
            "Event ID",
            "Trigger ID",
            "Name",
            "Last change",
            "Age",
            "Acknowledged",
            "Status",
        ]
        rows: RowsType = [
            [
                self.eventid,
                self.objectid,
                self.name,
                format_datetime(self.clock),
                self.age or "",
                self.acknowledged_str_cell,
                self.status_str_cell,
            ]
        ]
        return cols, rows


class Trigger(ZabbixAPIBaseModel):
    triggerid: str
    """Required for update operations."""
    description: Optional[str] = None
    """Required for create operations."""
    expression: Optional[str] = None
    """Required for create operations."""
    event_name: Optional[str] = None
    opdata: Optional[str] = None
    comments: Optional[str] = None
    error: Optional[str] = None
    flags: Optional[int] = None
    lastchange: Optional[datetime] = None
    priority: Optional[int] = None
    state: Optional[int] = None
    templateid: Optional[str] = None
    type: Optional[int] = None
    url: Optional[str] = None
    url_name: Optional[str] = None  # >6.0
    value: Optional[int] = None
    recovery_mode: Optional[int] = None
    recovery_expression: Optional[str] = None
    correlation_mode: Optional[int] = None
    correlation_tag: Optional[str] = None
    manual_close: Optional[int] = None
    uuid: Optional[str] = None
    hosts: list[Host] = []
    # NYI:
    # groups: List[HostGroup] = Field(
    #     default_factory=list, validation_alias=AliasChoices("groups", "hostgroups")
    # )
    # items
    # functions
    # dependencies
    # discoveryRule
    # lastEvent

    @computed_field
    @property
    def age(self) -> Optional[str]:
        """Returns the age of the event as a formatted string."""
        return age_from_datetime(self.lastchange)

    @computed_field
    @property
    def hostname(self) -> Optional[str]:
        """Returns the hostname of the trigger."""
        if self.hosts:
            return self.hosts[0].host
        return None

    @computed_field
    @property
    def severity(self) -> str:
        return TriggerPriority.string_from_value(self.priority)

    def __cols_rows__(self) -> ColsRowsType:
        cols = [
            "Trigger ID",
            "Host",
            "Description",
            "Severity",
            "Last Change",
            "Age",
        ]
        rows: RowsType = [
            [
                self.triggerid,
                self.hostname or "",
                self.description or "",
                self.severity,
                format_datetime(self.lastchange),
                self.age or "",
            ]
        ]
        return cols, rows


class Image(ZabbixAPIBaseModel):
    imageid: str
    name: str
    imagetype: int
    # NOTE: Optional so we can fetch an image without its data
    # This lets us get the IDs of all images without keeping the data in memory
    image: Optional[str] = None


class Map(ZabbixAPIBaseModel):
    sysmapid: str
    name: str
    height: int
    width: int
    backgroundid: Optional[str] = None  # will this be an empty string instead?
    # Other fields are omitted. We only use this for export and import.


class ImportRule(BaseModel):  # does not need to inherit from ZabbixAPIBaseModel
    createMissing: bool
    updateExisting: Optional[bool] = None
    deleteMissing: Optional[bool] = None


class ImportRules(ZabbixAPIBaseModel):
    discoveryRules: ImportRule
    graphs: ImportRule
    groups: Optional[ImportRule] = None  # < 6.2
    host_groups: Optional[ImportRule] = None  # >= 6.2
    hosts: ImportRule
    httptests: ImportRule
    images: ImportRule
    items: ImportRule
    maps: ImportRule
    mediaTypes: ImportRule
    template_groups: Optional[ImportRule] = None  # >= 6.2
    templateLinkage: ImportRule
    templates: ImportRule
    templateDashboards: ImportRule
    triggers: ImportRule
    valueMaps: ImportRule
    templateScreens: Optional[ImportRule] = None  # < 6.0
    applications: Optional[ImportRule] = None  # < 6.0
    screens: Optional[ImportRule] = None  # < 6.0

    model_config = ConfigDict(validate_assignment=True)

    @classmethod
    def get(
        cls,
        *,
        create_missing: bool = False,
        update_existing: bool = False,
        delete_missing: bool = False,
    ) -> ImportRules:
        """Create import rules given directives and Zabbix API version."""
        # Create/delete missing
        cd = ImportRule(createMissing=create_missing, deleteMissing=delete_missing)
        # Create/update missing
        cu = ImportRule(createMissing=create_missing, updateExisting=update_existing)
        # Create/update/delete missing
        cud = ImportRule(
            createMissing=create_missing,
            updateExisting=update_existing,
            deleteMissing=delete_missing,
        )
        rules = ImportRules(
            discoveryRules=cud,
            graphs=cud,
            hosts=cu,
            httptests=cud,
            images=cu,
            items=cud,
            maps=cu,
            mediaTypes=cu,
            templateLinkage=cd,
            templates=cu,
            templateDashboards=cud,
            triggers=cud,
            valueMaps=cud,
        )
        if cls.zabbix_version.release >= (6, 2, 0):
            rules.host_groups = cu
            rules.template_groups = cu
        else:
            rules.groups = ImportRule(createMissing=create_missing)

        if cls.zabbix_version.major < 6:
            rules.applications = cd
            rules.screens = cu
            rules.templateScreens = cud

        return rules


def resolve_forward_refs() -> None:
    """Certain models have forward references that need to be resolved.

    I.e. HostGroup has a field `hosts` that references the Host model,
    which is defined _after_ the HostGroup model. This function resolves
    those forward references so that we can serialize them properly.

    We do the simplest possible resolution here, which is to just
    rebuild all the models in the module. This is inefficient, but
    guarantees we won't have any runtime errors due to unresolved
    forward references.
    """
    for obj in globals().values():
        if not isinstance(obj, type):
            continue
        try:
            if not issubclass(obj, ZabbixAPIBaseModel):
                continue
        except TypeError:
            continue
        obj.model_rebuild()


resolve_forward_refs()