"""
Optional FastAPI router for the audit chain.

Provides a read-only HTTP endpoint to inspect the current chain state.
Only import this module if FastAPI is installed.

Usage::

    from fastapi import FastAPI
    from merkle_audit.fastapi import router

    app = FastAPI()
    app.include_router(router, prefix="/audit")

Endpoints:
    GET /audit/chain     — current leaf count + MMR root hash
"""
from __future__ import annotations

try:
    from fastapi import APIRouter
except ImportError as exc:  # pragma: no cover
    raise ImportError(
        "fastapi is required to use merkle_audit.fastapi. "
        "Install it with: pip install merkle-audit[fastapi]"
    ) from exc

from .chain import get_chain

router = APIRouter(tags=["Audit"])


@router.get("/chain")
async def get_chain_state() -> dict:
    """
    Return the current audit chain state.

    Response fields:
    - ``leaf_count``: number of entries appended so far
    - ``current_root``: hex-encoded SHA-256 MMR root (commits to all entries)

    The ``current_root`` changes with every append. Clients can poll this
    endpoint and compare roots over time to detect unexpected gaps or
    tampering.
    """
    chain = get_chain()
    return {
        "leaf_count": chain.leaf_count(),
        "current_root": chain.current_root(),
    }
