#!/usr/bin/env python3
"""
identity.py
-----------
Soul-anchored identity for BloomOS capsules.

Every capsule (task, file, model, seed) gets a unique soul ID
that provides cryptographic identity and trust anchoring.
"""

from __future__ import annotations

import time
import hashlib
from dataclasses import dataclass, field
from typing import Dict, Any, Optional


def blake2b_hex(data: bytes, digest_size: int = 32) -> str:
    """Compute BLAKE2b hex digest."""
    return hashlib.blake2b(data, digest_size=digest_size).hexdigest()


def sha256_hex(data: bytes) -> str:
    """Compute SHA256 hex digest."""
    return hashlib.sha256(data).hexdigest()


@dataclass
class SoulAnchor:
    """Soul-anchored identity for a capsule."""
    soul_id: str
    seed: str
    creator: str
    timestamp: float
    signature: str
    metadata: Dict[str, Any] = field(default_factory=dict)


def soul_id(seed: str, creator: str, timestamp: Optional[float] = None) -> str:
    """
    Generate a soul ID for a capsule.

    Soul IDs provide:
    - Unique cryptographic identity
    - Creator attribution
    - Temporal anchoring
    - Trust chain root

    Args:
        seed: Seed/task identifier
        creator: Creator identifier (user, system, agent)
        timestamp: Optional timestamp (uses current time if None)

    Returns:
        64-character hex soul ID
    """
    ts = timestamp or time.time()
    raw = f"{seed}:{creator}:{ts}".encode()
    return blake2b_hex(raw, digest_size=32)


def create_soul_anchor(
    seed: str,
    creator: str,
    metadata: Optional[Dict[str, Any]] = None
) -> SoulAnchor:
    """
    Create a full soul anchor with signature.

    Args:
        seed: Seed/task identifier
        creator: Creator identifier
        metadata: Additional metadata

    Returns:
        SoulAnchor object
    """
    ts = time.time()
    sid = soul_id(seed, creator, ts)

    # Create signature over soul_id + metadata
    sig_data = f"{sid}:{metadata or {}}".encode()
    signature = sha256_hex(sig_data)

    return SoulAnchor(
        soul_id=sid,
        seed=seed,
        creator=creator,
        timestamp=ts,
        signature=signature,
        metadata=metadata or {}
    )


def verify_soul_anchor(anchor: SoulAnchor) -> bool:
    """
    Verify a soul anchor's integrity.

    Args:
        anchor: SoulAnchor to verify

    Returns:
        True if signature is valid
    """
    # Recompute soul_id
    expected_sid = soul_id(anchor.seed, anchor.creator, anchor.timestamp)
    if expected_sid != anchor.soul_id:
        return False

    # Verify signature
    sig_data = f"{anchor.soul_id}:{anchor.metadata}".encode()
    expected_sig = sha256_hex(sig_data)

    return expected_sig == anchor.signature


# ============================================================================
# DEMO
# ============================================================================

def _demo():
    """Demonstrate soul-anchored identity."""
    print("=" * 70)
    print("SOUL-ANCHORED IDENTITY DEMO")
    print("=" * 70)
    print()

    # Create soul anchor
    anchor = create_soul_anchor(
        seed="task_001",
        creator="user:josh",
        metadata={"gate": "math_bias", "program": "ABCDGFGH"}
    )

    print("SOUL ANCHOR:")
    print(f"  Soul ID:   {anchor.soul_id[:32]}...")
    print(f"  Seed:      {anchor.seed}")
    print(f"  Creator:   {anchor.creator}")
    print(f"  Timestamp: {anchor.timestamp}")
    print(f"  Signature: {anchor.signature[:16]}...")
    print()

    # Verify
    is_valid = verify_soul_anchor(anchor)
    print(f"VERIFICATION: {'VALID' if is_valid else 'INVALID'}")
    print()

    # Show multiple souls are unique
    print("UNIQUENESS TEST:")
    souls = [
        soul_id("task_001", "user:josh"),
        soul_id("task_001", "user:laird"),
        soul_id("task_002", "user:josh"),
    ]
    for i, s in enumerate(souls):
        print(f"  Soul {i+1}: {s[:32]}...")

    print()
    print("=" * 70)


if __name__ == "__main__":
    _demo()
