"""CertiSigma SDK — Evidence & OTS utilities."""

import base64
from pathlib import Path
from typing import Optional, Union

MEMPOOL_BLOCK_URL = "https://mempool.space/block/"
MEMPOOL_TX_URL = "https://mempool.space/tx/"


def get_blockchain_url(evidence, type: str = "block") -> Optional[str]:
    """Return a mempool.space URL for the Bitcoin anchor.

    Args:
        evidence: EvidenceResult or raw dict from get_evidence().
        type: ``"block"`` for the block page, ``"tx"`` for the transaction page.

    Returns:
        URL string, or *None* if T2 data is not yet available.
    """
    t2 = evidence.t2 if hasattr(evidence, "t2") else evidence.get("t2")
    if not t2:
        return None

    if type == "tx":
        txid = t2.get("bitcoinTxid") if isinstance(t2, dict) else getattr(t2, "bitcoinTxid", None)
        return f"{MEMPOOL_TX_URL}{txid}" if txid else None

    block_hash = t2.get("bitcoinBlockHash") if isinstance(t2, dict) else getattr(t2, "bitcoinBlockHash", None)
    return f"{MEMPOOL_BLOCK_URL}{block_hash}" if block_hash else None


def save_ots_proof(evidence, path: Union[str, Path]) -> bool:
    """Save the raw OpenTimestamps ``.ots`` proof to a local file.

    Args:
        evidence: EvidenceResult or raw dict from get_evidence().
        path: Destination file path (should end in ``.ots``).

    Returns:
        *True* if saved successfully, *False* if T2/OTS proof is not available.
    """
    t2 = evidence.t2 if hasattr(evidence, "t2") else evidence.get("t2")
    if not t2:
        return False

    ots_b64 = t2.get("otsProof") if isinstance(t2, dict) else getattr(t2, "otsProof", None)
    if not ots_b64:
        return False

    ots_bytes = base64.b64decode(ots_b64)
    Path(path).write_bytes(ots_bytes)
    return True
