from __future__ import annotations

from dataclasses import asdict
from typing import Any, Dict, List, Optional, TYPE_CHECKING

from ..types import (
    ChainVerifyResult,
    ComplianceConfig,
    ExportParams,
    ExportResult,
    MerkleProof,
    MerkleRoot,
)

if TYPE_CHECKING:
    from ..client import Optropic


class Compliance:
    """Compliance, chain verification, and Merkle proof operations."""

    def __init__(self, client: Optropic) -> None:
        self._client = client

    def verify_chain(self) -> ChainVerifyResult:
        """Verify the integrity of the full audit chain."""
        data = self._client._request("POST", "/compliance/verify-chain")
        return ChainVerifyResult(**data)

    def list_merkle_roots(self) -> List[MerkleRoot]:
        """Return all Merkle roots."""
        data = self._client._request("GET", "/compliance/merkle-roots")
        return [MerkleRoot(**item) for item in data]

    def get_merkle_proof(self, event_id: str) -> MerkleProof:
        """Return a Merkle inclusion proof for a specific audit event."""
        data = self._client._request("GET", f"/compliance/merkle-proof/{event_id}")
        return MerkleProof(**data)

    def export_audit(self, params: Optional[ExportParams] = None) -> ExportResult:
        """Export audit data as a signed CSV."""
        query = asdict(params) if params else None
        data = self._client._request("GET", "/compliance/export", params=query)
        return ExportResult(**data)

    def get_config(self) -> ComplianceConfig:
        """Retrieve the current compliance configuration."""
        data = self._client._request("GET", "/compliance/config")
        return ComplianceConfig(**data)

    def update_config(self, mode: str) -> ComplianceConfig:
        """Update the compliance mode."""
        data = self._client._request(
            "PATCH",
            "/compliance/config",
            json={"compliance_mode": mode},
        )
        return ComplianceConfig(**data)
