"""REST API for AMCS verification."""

from __future__ import annotations

from typing import Optional, Union

from fastapi import FastAPI
from pydantic import BaseModel

from amcs.sdk.verify import verify_chain
from amcs.store.sqlite import SQLiteEventStore


class VerifyRequest(BaseModel):
    from_seq: int = 1
    to_seq: Optional[int] = None


class VerifyResponse(BaseModel):
    ok: bool
    checked_events: int
    failed_sequence: Optional[int] = None
    error: Optional[str] = None
    expected_root: Optional[str] = None
    actual_root: Optional[str] = None


def create_app(db_path: str = ":memory:") -> FastAPI:
    store = SQLiteEventStore(db_path)
    app = FastAPI(title="AMCS Verifier")

    @app.get("/agents/{agent_id}/root")
    def get_root(
        agent_id: str,
        seq: Optional[int] = None,
    ) -> dict[str, Union[str, int, None]]:
        return {
            "agent_id": agent_id,
            "sequence": seq,
            "memory_root": store.get_memory_root(agent_id, seq=seq),
        }

    @app.post("/agents/{agent_id}/verify", response_model=VerifyResponse)
    def verify(agent_id: str, req: VerifyRequest) -> VerifyResponse:
        result = verify_chain(
            store=store,
            agent_id=agent_id,
            from_seq=req.from_seq,
            to_seq=req.to_seq,
        )
        return VerifyResponse(**result.__dict__)

    return app
