"""
Harmonics Receipts - Audit trail for intent drift prediction.

These receipts track:
    - Handoff recordings (learning data)
    - Harmony predictions made
    - Path recommendations
    - Agent resonance updates
    - Risk warnings issued

Part of the Intent Harmonics system that predicts
handoff drift BEFORE it happens.
"""

from __future__ import annotations

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

from receipts.base import BaseReceipt


class HandoffRecordedReceipt(BaseReceipt):
    """
    Emitted when a handoff outcome is recorded.

    Records learning data for the harmonics engine.
    """

    receipt_type: str = "HandoffRecordedReceipt"
    domain: str = "organism"
    organ: str = "harmonics"

    # Handoff details
    source_agent: str
    target_agent: str
    intent_preserved: bool
    drift_magnitude: float
    friction: float

    # Context
    intent_type: Optional[str] = None
    relay_id: Optional[str] = None

    # State after recording
    resonance_harmony: float
    target_preservation_rate: float
    sample_count: int

    def __init__(
        self,
        *,
        source_agent: str,
        target_agent: str,
        intent_preserved: bool,
        drift_magnitude: float = 0.0,
        friction: float = 0.0,
        intent_type: Optional[str] = None,
        relay_id: Optional[str] = None,
        resonance_harmony: float,
        target_preservation_rate: float,
        sample_count: int,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"handoff_{source_agent}_{target_agent}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            source_agent=source_agent,
            target_agent=target_agent,
            intent_preserved=intent_preserved,
            drift_magnitude=drift_magnitude,
            friction=friction,
            intent_type=intent_type,
            relay_id=relay_id,
            resonance_harmony=resonance_harmony,
            target_preservation_rate=target_preservation_rate,
            sample_count=sample_count,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class HarmonicPredictionReceipt(BaseReceipt):
    """
    Emitted when a handoff prediction is made.

    Records drift risk assessment before handoff occurs.
    """

    receipt_type: str = "HarmonicPredictionReceipt"
    domain: str = "organism"
    organ: str = "harmonics"

    # Prediction target
    source_agent: str
    target_agent: str

    # Core prediction
    harmony_score: float
    drift_probability: float
    friction_estimate: float
    confidence: float

    # Risk analysis
    risk_level: str  # "low", "medium", "high", "critical"
    risk_factors: List[str]
    should_proceed: bool

    # Recommendations
    recommended_mitigations: List[str]
    alternative_targets: List[str]

    # Intent context
    intent_complexity: float
    intent_type: Optional[str] = None

    def __init__(
        self,
        *,
        source_agent: str,
        target_agent: str,
        harmony_score: float,
        drift_probability: float,
        friction_estimate: float,
        confidence: float,
        risk_level: str,
        risk_factors: List[str],
        should_proceed: bool,
        recommended_mitigations: List[str],
        alternative_targets: List[str],
        intent_complexity: float,
        intent_type: Optional[str] = None,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"prediction_{source_agent}_{target_agent}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            source_agent=source_agent,
            target_agent=target_agent,
            harmony_score=harmony_score,
            drift_probability=drift_probability,
            friction_estimate=friction_estimate,
            confidence=confidence,
            risk_level=risk_level,
            risk_factors=risk_factors,
            should_proceed=should_proceed,
            recommended_mitigations=recommended_mitigations,
            alternative_targets=alternative_targets,
            intent_complexity=intent_complexity,
            intent_type=intent_type,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class PathRecommendationReceipt(BaseReceipt):
    """
    Emitted when a handoff path is recommended.

    Records the optimal target selection from candidates.
    """

    receipt_type: str = "PathRecommendationReceipt"
    domain: str = "organism"
    organ: str = "harmonics"

    # Request
    source_agent: str
    candidate_targets: List[str]

    # Recommendation
    recommended_target: str
    harmony_score: float
    reasoning: List[str]

    # Alternative scores (for audit)
    all_scores: Dict[str, float]

    def __init__(
        self,
        *,
        source_agent: str,
        candidate_targets: List[str],
        recommended_target: str,
        harmony_score: float,
        reasoning: List[str],
        all_scores: Dict[str, float],
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"path_rec_{source_agent}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            source_agent=source_agent,
            candidate_targets=candidate_targets,
            recommended_target=recommended_target,
            harmony_score=harmony_score,
            reasoning=reasoning,
            all_scores=all_scores,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class AgentResonanceReceipt(BaseReceipt):
    """
    Emitted when agent pair resonance is updated.

    Records changes in mutual understanding between agents.
    """

    receipt_type: str = "AgentResonanceReceipt"
    domain: str = "organism"
    organ: str = "harmonics"

    # Agent pair
    agent_a: str
    agent_b: str

    # Resonance metrics
    harmony_score: float
    friction_coefficient: float
    confidence: float

    # Directional metrics
    a_to_b_preservation: float
    b_to_a_preservation: float

    # History
    sample_count: int
    successful_handoffs: int
    drift_handoffs: int

    # Change tracking
    harmony_delta: float = 0.0  # Change from previous

    def __init__(
        self,
        *,
        agent_a: str,
        agent_b: str,
        harmony_score: float,
        friction_coefficient: float,
        confidence: float,
        a_to_b_preservation: float,
        b_to_a_preservation: float,
        sample_count: int,
        successful_handoffs: int,
        drift_handoffs: int,
        harmony_delta: 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"resonance_{agent_a}_{agent_b}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            agent_a=agent_a,
            agent_b=agent_b,
            harmony_score=harmony_score,
            friction_coefficient=friction_coefficient,
            confidence=confidence,
            a_to_b_preservation=a_to_b_preservation,
            b_to_a_preservation=b_to_a_preservation,
            sample_count=sample_count,
            successful_handoffs=successful_handoffs,
            drift_handoffs=drift_handoffs,
            harmony_delta=harmony_delta,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


class DriftWarningReceipt(BaseReceipt):
    """
    Emitted when a high-risk handoff is warned about.

    Records that the system flagged a risky handoff.
    """

    receipt_type: str = "DriftWarningReceipt"
    domain: str = "organism"
    organ: str = "harmonics"

    # Warning context
    source_agent: str
    target_agent: str

    # Risk assessment
    risk_level: str  # "high" or "critical"
    harmony_score: float
    drift_probability: float

    # Warning details
    risk_factors: List[str]
    recommended_mitigations: List[str]
    alternative_targets: List[str]

    # Action taken
    warning_acknowledged: bool = False
    proceeded_anyway: bool = False

    def __init__(
        self,
        *,
        source_agent: str,
        target_agent: str,
        risk_level: str,
        harmony_score: float,
        drift_probability: float,
        risk_factors: List[str],
        recommended_mitigations: List[str],
        alternative_targets: List[str],
        warning_acknowledged: bool = False,
        proceeded_anyway: bool = False,
        ts: Optional[datetime] = None,
        parent_ids: Optional[List[str]] = None,
        **kwargs: Any,
    ):
        ts = ts or datetime.now(timezone.utc)
        receipt_id = f"drift_warning_{source_agent}_{target_agent}_{ts.strftime('%Y%m%d%H%M%S%f')}"
        super().__init__(
            receipt_id=receipt_id,
            source_agent=source_agent,
            target_agent=target_agent,
            risk_level=risk_level,
            harmony_score=harmony_score,
            drift_probability=drift_probability,
            risk_factors=risk_factors,
            recommended_mitigations=recommended_mitigations,
            alternative_targets=alternative_targets,
            warning_acknowledged=warning_acknowledged,
            proceeded_anyway=proceeded_anyway,
            ts=ts,
            parent_ids=parent_ids or [],
            **kwargs,
        )


__all__ = [
    "HandoffRecordedReceipt",
    "HarmonicPredictionReceipt",
    "PathRecommendationReceipt",
    "AgentResonanceReceipt",
    "DriftWarningReceipt",
]
