"""Sources: dating basis, authority and fact time.""" import re from dataclasses import dataclass from datetime import UTC, date, datetime, time, timedelta from enum import StrEnum from chemenu.domain.errors import FactTimeError class DatingBasis(StrEnum): """Where the fact time of a source comes from.""" CAPTURED = "captured" RECEIVED = "received" EMAIL_HEADER = "email_header" GIT_COMMIT = "git_commit" HTML_METADATA = "html_metadata" EXIF = "exif" FILENAME = "filename" CONTENT = "content" DOCUMENT_METADATA = "document_metadata" OPERATOR = "operator" class Authority(StrEnum): """How authoritative a source is. Enum order is the scale; no comparisons.""" OFFICIAL = "official" ORGANIZATION = "organization" THIRD_PARTY = "third_party" HEARSAY = "hearsay" class AuthorityForm(StrEnum): """Whether the source was written or spoken.""" WRITTEN = "written" ORAL = "oral" _DATE = r"[0-9]{4}-[0-9]{2}-[0-9]{2}" _POINT_RE = re.compile( rf"{_DATE}(?:T(?:[01][0-9]|2[0-3]):[0-9]{{2}}(?::[0-9]{{2}}(?:\.[0-9]{{1,6}})?)?" r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9]))?" ) def parse_point(text: str) -> date | datetime: """Parse a date (`YYYY-MM-DD`) or an ISO datetime with `T` and time zone.""" if _POINT_RE.fullmatch(text) is None: raise FactTimeError(f"invalid point in time: {text!r}") try: if "T" not in text: return date.fromisoformat(text) return datetime.fromisoformat(text) except (ValueError, OverflowError) as exc: raise FactTimeError(f"invalid point in time: {text!r}") from exc def format_point(point: date | datetime) -> str: """Inverse of `parse_point`.""" if not isinstance(point, datetime): return point.isoformat() offset = _offset(point) if offset.total_seconds() % 60 != 0: raise FactTimeError(f"unsupported UTC offset: {offset}") return point.isoformat() def _offset(point: datetime) -> timedelta: offset = point.utcoffset() if offset is None: raise FactTimeError("naive datetime is not allowed") return offset def _to_utc(point: date | datetime, *, end: bool) -> datetime: """Bound of a point in UTC; a date covers the whole UTC day.""" if isinstance(point, datetime): _offset(point) try: return point.astimezone(UTC) except OverflowError as exc: raise FactTimeError("point in time not representable in UTC") from exc return datetime.combine(point, time.max if end else time.min, tzinfo=UTC) @dataclass(frozen=True, slots=True, kw_only=True) class FactTime: """Interval in which a source's facts hold; `earliest` may be unknown.""" earliest: date | datetime | None latest: date | datetime basis: DatingBasis def __post_init__(self) -> None: end = _to_utc(self.latest, end=True) if self.earliest is not None and _to_utc(self.earliest, end=False) > end: raise FactTimeError("fact time starts after it ends") def precedes(self, other: FactTime) -> bool: """True if this ends strictly before `other` starts.""" if other.earliest is None: return False return _to_utc(self.latest, end=True) < _to_utc(other.earliest, end=False)