"""Minimal AMCS SDK client facade."""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from amcs.store.base import EventStore
from amcs.types import build_event_envelope

if TYPE_CHECKING:
    from amcs.sdk.verify import VerificationResult


@dataclass(frozen=True)
class AppendResult:
    agent_id: str
    sequence: int
    event_hash: str
    memory_root: str


class AMCSClient:
    """Convenience wrapper for appending events and reading memory roots."""

    def __init__(self, *, store: EventStore, agent_id: str) -> None:
        self._store = store
        self._agent_id = agent_id

    def append(
        self,
        event_type: str,
        payload: dict[str, Any],
        scope: str = "private",
        tags: list[str] | None = None,
    ) -> AppendResult:
        event = build_event_envelope(
            agent_id=self._agent_id,
            event_type=event_type,
            payload=payload,
            scope=scope,
            tags=tags,
        )
        result = self._store.append_event(self._agent_id, event)
        return AppendResult(
            agent_id=result["agent_id"],
            sequence=result["sequence"],
            event_hash=result["event_hash"],
            memory_root=result["memory_root"],
        )

    def get_memory_root(self, seq: int | None = None) -> str | None:
        return self._store.get_memory_root(self._agent_id, seq=seq)

    def verify_chain(
        self,
        from_seq: int = 1,
        to_seq: int | None = None,
    ) -> VerificationResult:
        from amcs.sdk.verify import verify_chain

        return verify_chain(
            self._store,
            self._agent_id,
            from_seq=from_seq,
            to_seq=to_seq,
        )

    def create_root_checkpoint(
        self,
        *,
        signer_private_key_b64: str,
        signer_kid: str,
        sequence: int | None = None,
        checkpointed_at: str | None = None,
    ) -> dict[str, Any]:
        from amcs.sdk.checkpoints import build_root_checkpoint

        checkpoint = build_root_checkpoint(
            store=self._store,
            agent_id=self._agent_id,
            signer_private_key_b64=signer_private_key_b64,
            signer_kid=signer_kid,
            sequence=sequence,
            checkpointed_at=checkpointed_at,
        )
        return checkpoint.as_dict()

    @staticmethod
    def verify_root_checkpoint(*, checkpoint: dict[str, Any], signer_public_key_b64: str) -> bool:
        from amcs.sdk.checkpoints import verify_root_checkpoint

        return verify_root_checkpoint(
            checkpoint=checkpoint,
            signer_public_key_b64=signer_public_key_b64,
        )
