"""
Market Receipts - Audit trail for cognitive economics.

These receipts track:
    - Value density computations
    - Attention bids submitted and resolved
    - Market state snapshots
    - Outcome predictions vs reality

Part of the Value-Density Market that makes the organism
economically intelligent.
"""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from receipts.base import BaseReceipt


class ValueDensityComputedReceipt(BaseReceipt):
    """
    Emitted when value density is computed for a task.

    Records the economic analysis of a potential task.
    """

    receipt_type: str = "ValueDensityComputedReceipt"
    domain: str = "organism"
    organ: str = "market"

    # Task
    task_id: str
    task_type: str

    # Estimates
    estimated_value: float
    estimated_cost: float
    value_density: float  # value / cost

    # Breakdown
    value_breakdown: Dict[str, float]  # base, urgency, unblocking, etc.
    cost_breakdown: Dict[str, float]  # cpu, memory, api, etc.

    # Context
    urgency: float
    symbiosis_bonus: float = 0.0

    def __init__(
        self,
        *,
        task_id: str,
        task_type: str,
        estimated_value: float,
        estimated_cost: float,
        value_density: float,
        value_breakdown: Dict[str, float],
        cost_breakdown: Dict[str, float],
        urgency: float,
        symbiosis_bonus: float = 0.0,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"density_{task_id}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            task_id=task_id,
            task_type=task_type,
            estimated_value=estimated_value,
            estimated_cost=estimated_cost,
            value_density=value_density,
            value_breakdown=value_breakdown,
            cost_breakdown=cost_breakdown,
            urgency=urgency,
            symbiosis_bonus=symbiosis_bonus,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class AttentionBidReceipt(BaseReceipt):
    """
    Emitted when an attention bid is submitted.

    Records a task's request for cognitive resources.
    """

    receipt_type: str = "AttentionBidReceipt"
    domain: str = "organism"
    organ: str = "market"

    # Bid details
    bid_id: str
    task_id: str
    task_type: str

    # Economics
    bid_price: float
    declared_value: float
    value_density: float
    urgency: float

    # Context
    goal_id: Optional[str] = None
    agent_id: Optional[str] = None
    ttl_seconds: float = 300.0

    def __init__(
        self,
        *,
        bid_id: str,
        task_id: str,
        task_type: str,
        bid_price: float,
        declared_value: float,
        value_density: float,
        urgency: float,
        goal_id: Optional[str] = None,
        agent_id: Optional[str] = None,
        ttl_seconds: float = 300.0,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"bid_{bid_id}"
        super().__init__(
            receipt_id=receipt_id,
            bid_id=bid_id,
            task_id=task_id,
            task_type=task_type,
            bid_price=bid_price,
            declared_value=declared_value,
            value_density=value_density,
            urgency=urgency,
            goal_id=goal_id,
            agent_id=agent_id,
            ttl_seconds=ttl_seconds,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class BidOutcomeReceipt(BaseReceipt):
    """
    Emitted when a bid is resolved (won, expired, withdrawn).

    Records the final state of an attention bid.
    """

    receipt_type: str = "BidOutcomeReceipt"
    domain: str = "organism"
    organ: str = "market"

    # Bid reference
    bid_id: str
    task_id: str
    task_type: str

    # Outcome
    status: str  # "won", "expired", "withdrawn", "outbid"
    success: bool

    # Predicted vs actual
    predicted_value: float
    actual_value: Optional[float] = None
    predicted_cost: float
    actual_cost: Optional[float] = None

    # Analysis
    prediction_error_value: Optional[float] = None
    prediction_error_cost: Optional[float] = None
    actual_density: Optional[float] = None

    def __init__(
        self,
        *,
        bid_id: str,
        task_id: str,
        task_type: str,
        status: str,
        success: bool,
        predicted_value: float,
        predicted_cost: float,
        actual_value: Optional[float] = None,
        actual_cost: Optional[float] = None,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"outcome_{bid_id}_{ts.strftime('%Y%m%d%H%M%S')}"

        # Compute errors if we have actuals
        error_value = None
        error_cost = None
        actual_density = None
        if actual_value is not None and actual_cost is not None:
            error_value = actual_value - predicted_value
            error_cost = actual_cost - predicted_cost
            actual_density = actual_value / max(actual_cost, 0.1)

        super().__init__(
            receipt_id=receipt_id,
            bid_id=bid_id,
            task_id=task_id,
            task_type=task_type,
            status=status,
            success=success,
            predicted_value=predicted_value,
            predicted_cost=predicted_cost,
            actual_value=actual_value,
            actual_cost=actual_cost,
            prediction_error_value=error_value,
            prediction_error_cost=error_cost,
            actual_density=actual_density,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class MarketStateReceipt(BaseReceipt):
    """
    Emitted periodically to record market state.

    Provides a snapshot of the cognitive economy.
    """

    receipt_type: str = "MarketStateReceipt"
    domain: str = "organism"
    organ: str = "market"

    # Queue state
    pending_bids: int
    active_bids: int
    total_bid_value: float

    # Pricing
    avg_value_density: float
    clearing_price: float
    market_pressure: float

    # Efficiency
    total_value_created: float
    total_cost_spent: float
    efficiency_ratio: float
    prediction_accuracy: float

    # Top performers
    best_roi_types: List[str]

    def __init__(
        self,
        *,
        pending_bids: int,
        active_bids: int,
        total_bid_value: float,
        avg_value_density: float,
        clearing_price: float,
        market_pressure: float,
        total_value_created: float,
        total_cost_spent: float,
        efficiency_ratio: float,
        prediction_accuracy: float,
        best_roi_types: Optional[List[str]] = None,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"market_state_{ts.strftime('%Y%m%d%H%M%S')}"
        super().__init__(
            receipt_id=receipt_id,
            pending_bids=pending_bids,
            active_bids=active_bids,
            total_bid_value=total_bid_value,
            avg_value_density=avg_value_density,
            clearing_price=clearing_price,
            market_pressure=market_pressure,
            total_value_created=total_value_created,
            total_cost_spent=total_cost_spent,
            efficiency_ratio=efficiency_ratio,
            prediction_accuracy=prediction_accuracy,
            best_roi_types=best_roi_types or [],
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


__all__ = [
    "ValueDensityComputedReceipt",
    "AttentionBidReceipt",
    "BidOutcomeReceipt",
    "MarketStateReceipt",
]
