"""
Agent Sovereignty Receipts

Constitutional audit trail for agent identity and power claims.

Each receipt documents a moment in the political life of an agent:
- Identity issuance
- Power claims filing
- Conflicts detection
- Arbitration outcomes
"""

from typing import Any, Dict, List, Optional
from datetime import datetime, timezone
from pydantic import BaseModel, Field
from receipts.models import BaseReceipt


# ─────────────────────────────────────────────────────────────────────
# Receipt Models
# ─────────────────────────────────────────────────────────────────────

class AgentIdentityIssuedReceipt(BaseReceipt):
    """
    Emitted when an agent's identity contract is issued.

    This is the constitutional birth certificate.
    """
    type: str = Field(default="agent_identity_issued", frozen=True)

    agent_id: str
    agent_name: str
    agent_type: str
    status: str = "active"
    identity_hash: str
    trust_score: float = 0.5
    capabilities: List[str] = Field(default_factory=list)
    prohibited_domains: List[str] = Field(default_factory=list)

    class Config:
        json_schema_extra = {
            "description": "Agent constitutional identity issued",
            "example": {
                "agent_id": "eng-0x1a4b2c",
                "agent_name": "Engineer",
                "agent_type": "code_agent",
                "capabilities": ["python_refactor", "code_review"],
                "prohibited_domains": ["direct_execution"],
            }
        }


class PowerClaimFiledReceipt(BaseReceipt):
    """
    Emitted when an agent files a power claim on a domain.

    This is the assertion of jurisdiction.
    """
    type: str = Field(default="power_claim_filed", frozen=True)

    claim_id: str
    agent_id: str
    domain: str
    scope: Dict[str, Any] = Field(default_factory=dict)
    justification: str
    status: str = "filed"
    confidence: float
    priority: int

    class Config:
        json_schema_extra = {
            "description": "Agent filed power claim on domain",
            "example": {
                "claim_id": "claim-abc123",
                "agent_id": "eng-0x1a4b2c",
                "domain": "python_refactor",
                "scope": {"file_patterns": ["*.py"], "complexity_threshold": 0.5},
                "justification": "5+ years experience, 98% success rate",
                "status": "filed",
            }
        }


class PowerClaimVerifiedReceipt(BaseReceipt):
    """
    Emitted when Guardian verifies a power claim.

    This is the constitutional approval.
    """
    type: str = Field(default="power_claim_verified", frozen=True)

    claim_id: str
    agent_id: str
    domain: str
    guardian_signature: str
    verified_at: str

    class Config:
        json_schema_extra = {
            "description": "Guardian verified power claim",
            "example": {
                "claim_id": "claim-abc123",
                "agent_id": "eng-0x1a4b2c",
                "domain": "python_refactor",
                "guardian_signature": "sig_0x...",
                "verified_at": "2025-12-02T12:00:00Z",
            }
        }


class JurisdictionConflictDetectedReceipt(BaseReceipt):
    """
    Emitted when multiple agents claim the same domain.

    This triggers arbitration.
    """
    type: str = Field(default="jurisdiction_conflict_detected", frozen=True)

    domain: str
    conflicting_claims: List[Dict[str, str]] = Field(default_factory=list)
    claimant_agents: List[str]
    severity: str = "medium"  # low, medium, high
    action_required: str = "arbitration"

    class Config:
        json_schema_extra = {
            "description": "Multiple agents claim same domain",
            "example": {
                "domain": "test_execution",
                "conflicting_claims": [
                    {"claim_id": "claim-001", "agent_id": "qa-1", "priority": 7},
                    {"claim_id": "claim-002", "agent_id": "qa-2", "priority": 6},
                ],
                "claimant_agents": ["qa-1", "qa-2"],
                "severity": "high",
                "action_required": "arbitration",
            }
        }


class AgentStatusChangedReceipt(BaseReceipt):
    """
    Emitted when an agent's status changes.

    Status transitions: UNBORN → ACTIVE → SUSPENDED/RETIRED/QUARANTINED
    """
    type: str = Field(default="agent_status_changed", frozen=True)

    agent_id: str
    agent_name: str
    previous_status: str
    new_status: str
    reason: Optional[str] = None
    effective_at: str

    class Config:
        json_schema_extra = {
            "description": "Agent status transitioned",
            "example": {
                "agent_id": "eng-0x1a4b2c",
                "agent_name": "Engineer",
                "previous_status": "active",
                "new_status": "suspended",
                "reason": "Policy violation detected",
                "effective_at": "2025-12-02T12:00:00Z",
            }
        }


class SovereigntyReportReceipt(BaseReceipt):
    """
    Emitted when a sovereignty report is generated.

    Periodic snapshot of agent political standing.
    """
    type: str = Field(default="sovereignty_report", frozen=True)

    agent_id: str
    agent_name: str
    status: str
    is_active: bool
    trust_score: float
    claims_total: int
    claims_verified: int
    claims_contested: int
    conflict_count: int

    class Config:
        json_schema_extra = {
            "description": "Sovereignty standing report",
            "example": {
                "agent_id": "eng-0x1a4b2c",
                "agent_name": "Engineer",
                "status": "active",
                "is_active": True,
                "trust_score": 0.92,
                "claims_total": 3,
                "claims_verified": 2,
                "claims_contested": 1,
                "conflict_count": 1,
            }
        }


# ─────────────────────────────────────────────────────────────────────
# Receipt Factory Functions
# ─────────────────────────────────────────────────────────────────────

def agent_identity_issued(
    agent_id: str,
    agent_name: str,
    agent_type: str,
    identity_hash: str,
    capabilities: List[str],
    prohibited_domains: List[str],
    trust_score: float = 0.5,
) -> AgentIdentityIssuedReceipt:
    """Factory: emit agent identity issued receipt."""
    return AgentIdentityIssuedReceipt(
        agent_id=agent_id,
        agent_name=agent_name,
        agent_type=agent_type,
        identity_hash=identity_hash,
        capabilities=capabilities,
        prohibited_domains=prohibited_domains,
        trust_score=trust_score,
    )


def power_claim_filed(
    claim_id: str,
    agent_id: str,
    domain: str,
    scope: Dict[str, Any],
    justification: str,
    confidence: float,
    priority: int,
) -> PowerClaimFiledReceipt:
    """Factory: emit power claim filed receipt."""
    return PowerClaimFiledReceipt(
        claim_id=claim_id,
        agent_id=agent_id,
        domain=domain,
        scope=scope,
        justification=justification,
        status="filed",
        confidence=confidence,
        priority=priority,
    )


def power_claim_verified(
    claim_id: str,
    agent_id: str,
    domain: str,
    guardian_signature: str,
) -> PowerClaimVerifiedReceipt:
    """Factory: emit power claim verified receipt."""
    return PowerClaimVerifiedReceipt(
        claim_id=claim_id,
        agent_id=agent_id,
        domain=domain,
        guardian_signature=guardian_signature,
        verified_at=datetime.now(timezone.utc).isoformat(),
    )


def jurisdiction_conflict_detected(
    domain: str,
    conflicting_claims: List[Dict[str, str]],
    claimant_agents: List[str],
    severity: str = "medium",
) -> JurisdictionConflictDetectedReceipt:
    """Factory: emit jurisdiction conflict detected receipt."""
    return JurisdictionConflictDetectedReceipt(
        domain=domain,
        conflicting_claims=conflicting_claims,
        claimant_agents=claimant_agents,
        severity=severity,
        action_required="arbitration",
    )


def agent_status_changed(
    agent_id: str,
    agent_name: str,
    previous_status: str,
    new_status: str,
    reason: Optional[str] = None,
) -> AgentStatusChangedReceipt:
    """Factory: emit agent status changed receipt."""
    return AgentStatusChangedReceipt(
        agent_id=agent_id,
        agent_name=agent_name,
        previous_status=previous_status,
        new_status=new_status,
        reason=reason,
        effective_at=datetime.now(timezone.utc).isoformat(),
    )


def sovereignty_report(
    agent_id: str,
    agent_name: str,
    status: str,
    is_active: bool,
    trust_score: float,
    claims_total: int,
    claims_verified: int,
    claims_contested: int,
    conflict_count: int,
) -> SovereigntyReportReceipt:
    """Factory: emit sovereignty report receipt."""
    return SovereigntyReportReceipt(
        agent_id=agent_id,
        agent_name=agent_name,
        status=status,
        is_active=is_active,
        trust_score=trust_score,
        claims_total=claims_total,
        claims_verified=claims_verified,
        claims_contested=claims_contested,
        conflict_count=conflict_count,
    )


# ─────────────────────────────────────────────────────────────────────
# Arbitration Court Receipts
# ─────────────────────────────────────────────────────────────────────

class JurisdictionRuledReceipt(BaseReceipt):
    """Receipt for Arbitration Court ruling on jurisdiction conflict."""
    type: str = Field(default="jurisdiction_ruled", frozen=True)

    case_id: str = Field(description="Arbitration case ID")
    domain: str = Field(description="Domain with conflict")
    claimant1_id: str = Field(description="First claimant agent ID")
    claimant2_id: str = Field(description="Second claimant agent ID")
    ruling: Optional[str] = Field(default=None, description="Ruling type (claimant1_wins, claimant2_wins, shared, blocked)")
    winner_id: Optional[str] = Field(default=None, description="Agent ID of jurisdiction winner (if applicable)")
    ruling_score: float = Field(default=0.0, description="Confidence in ruling [0, 1]")
    reasoning: str = Field(default="", description="Court reasoning for ruling")

    class Config:
        json_schema_extra = {
            "description": "Arbitration Court ruled on jurisdiction conflict",
            "example": {
                "case_id": "case_python_refactor_eng1_eng2",
                "domain": "python_refactor",
                "claimant1_id": "eng-001",
                "claimant2_id": "eng-002",
                "ruling": "claimant1_wins",
                "winner_id": "eng-001",
                "ruling_score": 0.78,
                "reasoning": "Claimant 1 has higher priority and trust score"
            }
        }


class ArbitrationAppealReceipt(BaseReceipt):
    """Receipt for appeal of Arbitration Court ruling."""
    type: str = Field(default="arbitration_appeal", frozen=True)

    case_id: str = Field(description="Arbitration case ID")
    domain: str = Field(description="Domain with conflict")
    original_ruling: str = Field(description="Original court ruling")
    appeal_reason: str = Field(description="Reason for Guardian appeal")
    appeal_decision: Optional[str] = Field(default=None, description="Guardian decision (uphold or overturn)")
    guardian_reasoning: str = Field(default="", description="Guardian's reasoning")

    class Config:
        json_schema_extra = {
            "description": "Appeal of Arbitration Court ruling",
            "example": {
                "case_id": "case_python_refactor_eng1_eng2",
                "domain": "python_refactor",
                "original_ruling": "claimant1_wins",
                "appeal_reason": "Claimant 2 has newer skill data not considered",
                "appeal_decision": "uphold",
                "guardian_reasoning": "Original ruling stands with available evidence"
            }
        }
