"""
External timestamp anchoring for the attestation chain.

Provides two mechanisms to externally prove that the chain head existed
before a given time:

1. RFC 3161 TSA (Timestamping Authority) — automated, requires network
2. Manual anchors — export chain head hash for manual submission to any
   external witness (blockchain, newspaper, tweet, TSA via email)

A single anchor for the chain head implicitly timestamps every record
that preceded it, because the chain is append-only with hash linkage.
"""

from __future__ import annotations

import hashlib
import json
from datetime import UTC, datetime
from pathlib import Path

import soosef.paths as _paths


def get_chain_head_anchor() -> dict:
    """Get the current chain head hash and metadata for anchoring.

    Returns a dict suitable for submission to any external timestamp service.
    """
    from soosef.federation.chain import ChainStore

    store = ChainStore(_paths.CHAIN_DIR)
    state = store.state()

    if state is None:
        return {"error": "Chain is empty"}

    return {
        "anchor_version": "1",
        "chain_id": state.chain_id.hex(),
        "head_index": state.head_index,
        "head_hash": state.head_hash.hex(),
        "record_count": state.record_count,
        "timestamp": datetime.now(UTC).isoformat(),
        "digest": hashlib.sha256(
            f"{state.chain_id.hex()}:{state.head_hash.hex()}:{state.head_index}".encode()
        ).hexdigest(),
    }


def submit_rfc3161(anchor: dict, tsa_url: str = "https://freetsa.org/tsr") -> dict:
    """Submit a chain head hash to an RFC 3161 Timestamping Authority.

    Args:
        anchor: Output from get_chain_head_anchor().
        tsa_url: URL of the TSA service.

    Returns:
        Dict with the TSA response token (base64-encoded DER) and metadata.
    """
    import base64
    import urllib.request

    # Build the timestamp request (SHA-256 digest)
    digest_bytes = bytes.fromhex(anchor["digest"])

    # RFC 3161 TimeStampReq structure (minimal DER encoding)
    # This is a simplified approach — for production, use pyasn1 or similar
    # We submit the hash directly and get back a signed timestamp token
    req_data = digest_bytes

    try:
        req = urllib.request.Request(
            tsa_url,
            data=req_data,
            headers={
                "Content-Type": "application/timestamp-query",
            },
        )
        resp = urllib.request.urlopen(req, timeout=30)
        token = resp.read()

        return {
            "tsa_url": tsa_url,
            "submitted_at": datetime.now(UTC).isoformat(),
            "digest": anchor["digest"],
            "head_index": anchor["head_index"],
            "token_b64": base64.b64encode(token).decode(),
            "token_size": len(token),
            "success": True,
        }
    except Exception as e:
        return {
            "tsa_url": tsa_url,
            "error": str(e),
            "success": False,
        }


def save_anchor(anchor: dict, tsa_response: dict | None = None) -> Path:
    """Save an anchor record to the anchors directory.

    Returns the path to the saved anchor file.
    """
    anchors_dir = _paths.CHAIN_DIR / "anchors"
    anchors_dir.mkdir(parents=True, exist_ok=True)

    record = {
        "anchor": anchor,
        "tsa": tsa_response,
        "saved_at": datetime.now(UTC).isoformat(),
    }

    filename = f"anchor_{anchor['head_index']:06d}_{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}.json"
    path = anchors_dir / filename
    path.write_text(json.dumps(record, indent=2))
    return path


def load_anchors() -> list[dict]:
    """Load all saved anchor records, newest first."""
    anchors_dir = _paths.CHAIN_DIR / "anchors"
    if not anchors_dir.exists():
        return []

    anchors = []
    for path in sorted(anchors_dir.glob("anchor_*.json"), reverse=True):
        try:
            anchors.append(json.loads(path.read_text()))
        except Exception:
            continue
    return anchors


def export_anchor_for_manual_submission(anchor: dict) -> str:
    """Format an anchor for manual external submission.

    Returns a compact string suitable for tweeting, emailing to a TSA,
    publishing in a newspaper classified, or submitting to a blockchain.
    """
    return (
        f"SooSeF Chain Anchor\n"
        f"Chain: {anchor['chain_id'][:16]}...\n"
        f"Head:  #{anchor['head_index']} ({anchor['record_count']} records)\n"
        f"Hash:  {anchor['digest']}\n"
        f"Time:  {anchor['timestamp']}\n"
        f"\n"
        f"This hash proves the entire chain existed before this timestamp.\n"
        f"Verify: soosef chain verify && soosef chain anchor check {anchor['digest']}"
    )
