#!/usr/bin/env python3
"""
Vault Client - Tile access for CDC
===================================

Fetches tiles from Crystal Vault or generates on-the-fly from seed.
"""
import os
import hashlib
from pathlib import Path
from typing import Dict, Any, Optional


class VaultClient:
    """Client for vault tile access"""

    def __init__(self, vault_path: Optional[str] = None, seed_path: Optional[str] = None):
        """
        Initialize vault client.

        Args:
            vault_path: Path to vault directory
            seed_path: Path to .hxz seed file
        """
        self.vault_path = Path(vault_path) if vault_path else None
        self.seed_path = Path(seed_path) if seed_path else None
        self.seed_bytes = None

        # Load seed if provided
        if self.seed_path and self.seed_path.exists():
            self.seed_bytes = self.seed_path.read_bytes()

    def get_segment(self, seed_sha256: str, anchor_key: str) -> Dict[str, Any]:
        """
        Get vault segment/tile for given anchor.

        Args:
            seed_sha256: Seed SHA256 hash
            anchor_key: Anchor key from FibPi3D

        Returns:
            Dict with "bytes" and "sha256" of tile
        """
        # Try vault-backed access first
        if self.vault_path and self.vault_path.exists():
            # Try to load from vault by anchor
            # For now, generate deterministically from seed + anchor
            pass

        # Deterministic tile generation from seed + anchor
        # This is the "compute from anchor" path
        tile_bytes = self._generate_tile(seed_sha256, anchor_key)
        tile_sha = hashlib.sha256(tile_bytes).hexdigest()

        return {
            "bytes": tile_bytes,
            "sha256": tile_sha,
            "anchor_key": anchor_key,
            "method": "deterministic_seed",
        }

    def _generate_tile(self, seed_sha256: str, anchor_key: str, tile_size: int = 4096) -> bytes:
        """
        Generate tile deterministically from seed + anchor.

        Args:
            seed_sha256: Seed SHA256
            anchor_key: Anchor key
            tile_size: Size of tile in bytes

        Returns:
            Tile bytes
        """
        # Use SHAKE-256 XOF to generate deterministic tile
        # Domain separation: seed || anchor_key
        shake = hashlib.shake_256()
        shake.update(b"HELIX|tile|v1|")
        shake.update(bytes.fromhex(seed_sha256))
        shake.update(anchor_key.encode())

        # If we have seed bytes, mix them in
        if self.seed_bytes:
            shake.update(self.seed_bytes[:256])  # Use first 256 bytes of seed

        # Generate tile
        tile_bytes = shake.digest(tile_size)
        return tile_bytes


def ensure_vault_client(vault_path: Optional[str] = None, seed_path: Optional[str] = None) -> VaultClient:
    """
    Ensure vault client is initialized.

    Args:
        vault_path: Path to vault directory
        seed_path: Path to seed file

    Returns:
        VaultClient instance
    """
    # Use env defaults if not provided
    if not vault_path:
        vault_path = os.environ.get("HELIX_VAULT_PATH")
    if not seed_path:
        seed_path = os.environ.get("FLOWTORCH_SEED_PATH")

    return VaultClient(vault_path=vault_path, seed_path=seed_path)
