"""BloomOS Receipt Generation - Cryptographic Provenance"""

import hashlib
import json
from datetime import datetime, timezone
from typing import Dict, Any


def generate_task_id(request: Dict[str, Any]) -> str:
    """
    Generate unique task ID from request using SHA256.

    Args:
        request: TaskRequest dict

    Returns:
        SHA256 hash (first 16 chars)
    """
    timestamp = datetime.now(timezone.utc).isoformat()
    payload = json.dumps({
        "request": request,
        "timestamp": timestamp
    }, sort_keys=True)
    hash_obj = hashlib.sha256(payload.encode('utf-8'))
    return hash_obj.hexdigest()[:16]


def generate_receipt(
    task_id: str,
    request: Dict[str, Any],
    result: Dict[str, Any],
    experiment_ref: str = "EXPERIMENT_1B_POS4_FOCUS"
) -> Dict[str, Any]:
    """
    Generate cryptographic receipt for task execution.

    Args:
        task_id: Unique task identifier
        request: Original TaskRequest dict
        result: TaskResult dict
        experiment_ref: Reference to experiment that validates gate (default: Exp 1b)

    Returns:
        Receipt dict with SHA256 hash, timestamps, and experiment provenance
    """
    timestamp = datetime.now(timezone.utc).isoformat()

    receipt_payload = {
        "task_id": task_id,
        "timestamp": timestamp,
        "request": request,
        "result": {
            "status": result.get("status"),
            "gate_used": result.get("gate_used"),
            "anchors_used": result.get("anchors_used"),
            "logits_mean": result.get("logits_mean"),
            "logits_std": result.get("logits_std"),
        },
        "experiment_ref": experiment_ref,
        "bloomos_version": "v0.1.0"
    }

    # Compute SHA256 of entire receipt
    receipt_json = json.dumps(receipt_payload, sort_keys=True)
    receipt_hash = hashlib.sha256(receipt_json.encode('utf-8')).hexdigest()

    receipt_payload["receipt_hash"] = receipt_hash

    return receipt_payload


def verify_receipt(receipt: Dict[str, Any]) -> bool:
    """
    Verify receipt integrity by recomputing SHA256 hash.

    Args:
        receipt: Receipt dict with receipt_hash field

    Returns:
        True if hash matches, False otherwise
    """
    claimed_hash = receipt.get("receipt_hash")
    if not claimed_hash:
        return False

    # Remove hash and recompute
    receipt_copy = receipt.copy()
    del receipt_copy["receipt_hash"]

    receipt_json = json.dumps(receipt_copy, sort_keys=True)
    computed_hash = hashlib.sha256(receipt_json.encode('utf-8')).hexdigest()

    return claimed_hash == computed_hash
