a00fa96module-09: add ex1
1 file changed, +94, -0
author
mogi <git@mogiya.dev> on 23-05-2026 02:44 UTC+1
committer
mogi <git@mogiya.dev> on 23-05-2026 02:46 UTC+1
parent7be323a
    @@ -0,0 +1,94 @@
   1+import json
   2+from datetime import datetime
   3+from enum import Enum
   4+from typing import Optional
   5+from pydantic import BaseModel, Field, ValidationError, model_validator
   6+
   7+
   8+class ContactType(Enum):
   9+    radio = "radio"
  10+    visual = "visual"
  11+    physical = "physical"
  12+    telepathic = "telepathic"
  13+
  14+
  15+class AlienContact(BaseModel):
  16+    contact_id: str = Field(..., min_length=5, max_length=15)
  17+    timestamp: datetime
  18+    location: str = Field(..., min_length=3, max_length=100)
  19+    contact_type: ContactType
  20+    signal_strength: float = Field(..., ge=0.0, le=10.0)
  21+    duration_minutes: int = Field(..., ge=1, le=1440)
  22+    witness_count: int = Field(..., ge=1, le=100)
  23+    message_received: Optional[str] = Field(default=None, max_length=500)
  24+    is_verified: bool = False
  25+
  26+    @model_validator(mode="after")
  27+    def apply_business_rules(self) -> "AlienContact":
  28+        if not self.contact_id.startswith("AC"):
  29+            raise ValueError("contact_id must start with 'AC'")
  30+        if self.contact_type == ContactType.physical and not self.is_verified:
  31+            raise ValueError(
  32+                "Physical contact reports must be verified (is_verified=True)"
  33+            )
  34+        if (
  35+            self.contact_type == ContactType.telepathic
  36+            and self.witness_count < 3
  37+        ):
  38+            raise ValueError(
  39+                "Telepathic contact requires at least 3 witnesses"
  40+            )
  41+        if self.signal_strength > 7.0 and not self.message_received:
  42+            raise ValueError(
  43+                f"Signal strength {self.signal_strength} "
  44+                f"> 7.0 requires a message_received entry"
  45+            )
  46+        return self
  47+
  48+
  49+def load_json(path: str) -> list:
  50+    try:
  51+        with open(path) as f:
  52+            return json.load(f)
  53+    except FileNotFoundError:
  54+        print(f"Error: '{path}' not found")
  55+        return []
  56+    except json.JSONDecodeError as exc:
  57+        print(f"Error: invalid JSON in '{path}' — {exc}")
  58+        return []
  59+
  60+
  61+def main() -> None:
  62+    print("Alien Contact Log Validation")
  63+
  64+    records = load_json("alien_contacts.json") + load_json(
  65+        "invalid_contacts.json"
  66+    )
  67+
  68+    for record in records:
  69+        try:
  70+            contact = AlienContact.model_validate(record)
  71+            print("=" * 50)
  72+            print("Valid contact report:")
  73+            print(f"ID: {contact.contact_id}")
  74+            print(f"Type: {contact.contact_type.value}")
  75+            print(f"Location: {contact.location}")
  76+            print(f"Signal: {contact.signal_strength}/10")
  77+            print(f"Duration: {contact.duration_minutes} minutes")
  78+            print(f"Witnesses: {contact.witness_count}")
  79+            print(
  80+                f"Message: '{contact.message_received}'"
  81+                if contact.message_received
  82+                else "Message: None"
  83+            )
  84+            print()
  85+        except ValidationError as exc:
  86+            msg = exc.errors()[0]["msg"].removeprefix("Value error, ")
  87+            print("=" * 50)
  88+            print("Expected validation error:")
  89+            print(msg)
  90+            print()
  91+
  92+
  93+if __name__ == "__main__":
  94+    main()