"""The boundary contract is shared by the CLI, API and storage implementations."""
from __future__ import annotations

from datetime import datetime, timezone
import hashlib
import json
import re
from typing import Annotated, Literal, Protocol

from pydantic import BaseModel, ConfigDict, Field, field_validator


class RecordInput(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True)
    source: Annotated[str, Field(min_length=1, max_length=64)]
    timestamp: datetime
    level: Literal["INFO", "WARN", "ERROR"]
    message: Annotated[str, Field(max_length=512)]

    @field_validator("timestamp")
    @classmethod
    def require_timezone(cls, value: datetime) -> datetime:
        if value.tzinfo is None or value.utcoffset() is None:
            raise ValueError("timestamp must include timezone")
        return value.astimezone(timezone.utc)


class ImportInput(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True)
    # frozen prevents rebinding; tuple also prevents mutating the batch after admission.
    records: Annotated[tuple[RecordInput, ...], Field(min_length=1, max_length=64)]

    def fingerprint(self) -> str:
        # Contract: record order is significant; object key order is not.
        # Defaults and UTC normalization are applied before hashing.
        encoded = json.dumps(self.model_dump(mode="json"), sort_keys=True,
                             separators=(",", ":"), ensure_ascii=False).encode("utf-8")
        return hashlib.sha256(encoded).hexdigest()


class ImportResult(BaseModel):
    operation_id: str
    count: int


class ConflictError(Exception):
    """The same operation key was reused for a different payload."""


def validate_operation_key(key: str) -> str:
    if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", key):
        raise ValueError("operation key must be 1..64 ASCII letters, digits, _ or -")
    return key


class Store(Protocol):
    def ingest(self, owner: str, key: str, payload: ImportInput) -> ImportResult: ...
    def records(self, owner: str, after: int, limit: int) -> list[dict[str, object]]: ...
    def close(self) -> None: ...
