"""
SOVR SDK Data Models v3.0.0
Aligned with @sovr/sdk Node.js v3.0.0 types
"""

from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List


@dataclass
class GateCheckResult:
    """Response from gate-check endpoint."""
    decision_id: str
    allowed: bool
    requires_approval: bool
    reason: str
    risk_score: float
    value_score: float
    policy_version: str
    trace_id: str
    degraded: Optional[bool] = None
    degrade_reason: Optional[str] = None
    mode: Optional[str] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "GateCheckResult":
        return cls(
            decision_id=data.get("decision_id", ""),
            allowed=data.get("allowed", False),
            requires_approval=data.get("requires_approval", False),
            reason=data.get("reason", ""),
            risk_score=data.get("risk_score", 0.0),
            value_score=data.get("value_score", 0.0),
            policy_version=data.get("policy_version", ""),
            trace_id=data.get("trace_id", ""),
            degraded=data.get("degraded"),
            degrade_reason=data.get("degrade_reason"),
            mode=data.get("mode"),
        )


@dataclass
class ApprovalResult:
    """Response from request-approval endpoint."""
    approval_id: str
    status: str  # 'pending' | 'approved' | 'rejected' | 'expired'
    approval_url: str
    estimated_wait_seconds: int
    expires_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApprovalResult":
        return cls(
            approval_id=data.get("approval_id", ""),
            status=data.get("status", "pending"),
            approval_url=data.get("approval_url", ""),
            estimated_wait_seconds=data.get("estimated_wait_seconds", 0),
            expires_at=data.get("expires_at", 0),
        )


@dataclass
class PermitResult:
    """Response from grant-permit endpoint."""
    permit_id: str
    jti: str
    decision_id: str
    expires_at: int
    signature: str
    public_key: str

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PermitResult":
        return cls(
            permit_id=data.get("permit_id", ""),
            jti=data.get("jti", ""),
            decision_id=data.get("decision_id", ""),
            expires_at=data.get("expires_at", 0),
            signature=data.get("signature", ""),
            public_key=data.get("public_key", ""),
        )


@dataclass
class ReceiptResult:
    """Response from submit-receipt endpoint."""
    receipt_id: str
    trust_hash: str
    evidence_hash: str
    chain_position: int
    recorded_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ReceiptResult":
        return cls(
            receipt_id=data.get("receipt_id", ""),
            trust_hash=data.get("trust_hash", ""),
            evidence_hash=data.get("evidence_hash", ""),
            chain_position=data.get("chain_position", 0),
            recorded_at=data.get("recorded_at", 0),
        )


@dataclass
class ReplayResult:
    """Response from replay-decision endpoint."""
    replay_id: str
    original_decision: Dict[str, Any]
    replayed_decision: Dict[str, Any]
    match: bool
    drift_detected: bool
    diff: Optional[List[Dict[str, Any]]] = None
    trace_id: str = ""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ReplayResult":
        return cls(
            replay_id=data.get("replay_id", ""),
            original_decision=data.get("original_decision", {}),
            replayed_decision=data.get("replayed_decision", {}),
            match=data.get("match", False),
            drift_detected=data.get("drift_detected", False),
            diff=data.get("diff"),
            trace_id=data.get("trace_id", ""),
        )


@dataclass
class ExportBundleResult:
    """Response from export-bundle endpoint."""
    bundle_id: str
    decision_id: str
    format: str
    bundle_hash: str
    merkle_root: str
    evidence_count: int
    sealed_at: int
    download_url: str
    verification_url: str
    expires_at: int
    trace_id: str = ""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ExportBundleResult":
        return cls(
            bundle_id=data.get("bundle_id", ""),
            decision_id=data.get("decision_id", ""),
            format=data.get("format", "json"),
            bundle_hash=data.get("bundle_hash", ""),
            merkle_root=data.get("merkle_root", ""),
            evidence_count=data.get("evidence_count", 0),
            sealed_at=data.get("sealed_at", 0),
            download_url=data.get("download_url", ""),
            verification_url=data.get("verification_url", ""),
            expires_at=data.get("expires_at", 0),
            trace_id=data.get("trace_id", ""),
        )


@dataclass
class ScanFinding:
    """A single finding from content scanning."""
    pattern: str
    severity: str  # 'critical' | 'high' | 'medium' | 'low' | 'info'
    category: str
    description: str
    line: Optional[int] = None
    match: Optional[str] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ScanFinding":
        return cls(
            pattern=data.get("pattern", ""),
            severity=data.get("severity", "info"),
            category=data.get("category", ""),
            description=data.get("description", ""),
            line=data.get("line"),
            match=data.get("match"),
        )


@dataclass
class ScanResult:
    """Response from OpenGuard content scan."""
    scan_id: str
    safe: bool
    risk_score: float
    findings: List[ScanFinding]
    duration_ms: int
    timestamp: int
    fact_anchor: Optional[Dict[str, Any]] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ScanResult":
        findings = [ScanFinding.from_dict(f) for f in data.get("findings", [])]
        return cls(
            scan_id=data.get("scan_id", ""),
            safe=data.get("safe", True),
            risk_score=data.get("risk_score", 0.0),
            findings=findings,
            duration_ms=data.get("duration_ms", 0),
            timestamp=data.get("timestamp", 0),
            fact_anchor=data.get("fact_anchor"),
        )


@dataclass
class QuickScanResult:
    """Response from OpenGuard quick scan."""
    safe: bool
    risk_score: float
    finding_count: int
    severity_summary: Dict[str, int]
    duration_ms: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "QuickScanResult":
        return cls(
            safe=data.get("safe", True),
            risk_score=data.get("risk_score", 0.0),
            finding_count=data.get("finding_count", 0),
            severity_summary=data.get("severity_summary", {}),
            duration_ms=data.get("duration_ms", 0),
        )


@dataclass
class ScanStats:
    """OpenGuard scanning statistics."""
    total_scans: int
    total_findings: int
    by_severity: Dict[str, int]
    by_category: Dict[str, int]
    avg_duration_ms: float

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ScanStats":
        return cls(
            total_scans=data.get("total_scans", 0),
            total_findings=data.get("total_findings", 0),
            by_severity=data.get("by_severity", {}),
            by_category=data.get("by_category", {}),
            avg_duration_ms=data.get("avg_duration_ms", 0.0),
        )


@dataclass
class KillSwitchStatus:
    """KillSwitch status response."""
    active: bool
    level: int  # 0-5
    level_description: str
    reason: str
    triggered_at: Optional[int] = None
    triggered_by: Optional[str] = None
    auto_recovery: bool = False

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "KillSwitchStatus":
        return cls(
            active=data.get("active", False),
            level=data.get("level", 0),
            level_description=data.get("level_description", ""),
            reason=data.get("reason", ""),
            triggered_at=data.get("triggered_at"),
            triggered_by=data.get("triggered_by"),
            auto_recovery=data.get("auto_recovery", False),
        )


@dataclass
class KillSwitchTriggerResult:
    """KillSwitch trigger response."""
    success: bool
    previous_level: int
    new_level: int
    audit_event_id: str
    triggered_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "KillSwitchTriggerResult":
        return cls(
            success=data.get("success", False),
            previous_level=data.get("previous_level", 0),
            new_level=data.get("new_level", 0),
            audit_event_id=data.get("audit_event_id", ""),
            triggered_at=data.get("triggered_at", 0),
        )


@dataclass
class KillSwitchRecoverResult:
    """KillSwitch recovery response."""
    success: bool
    previous_level: int
    new_level: int
    audit_event_id: str
    recovered_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "KillSwitchRecoverResult":
        return cls(
            success=data.get("success", False),
            previous_level=data.get("previous_level", 0),
            new_level=data.get("new_level", 0),
            audit_event_id=data.get("audit_event_id", ""),
            recovered_at=data.get("recovered_at", 0),
        )


@dataclass
class PolicyValidateResult:
    """Policy validation response."""
    valid: bool
    errors: List[str]

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PolicyValidateResult":
        return cls(
            valid=data.get("valid", False),
            errors=data.get("errors", []),
        )


@dataclass
class PolicyVersionResult:
    """Policy version response."""
    id: str
    name: str
    version: str
    rule_count: int
    default_action: str
    created_at: int
    author: Optional[str] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PolicyVersionResult":
        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            version=data.get("version", ""),
            rule_count=data.get("rule_count", 0),
            default_action=data.get("default_action", "deny"),
            created_at=data.get("created_at", 0),
            author=data.get("author"),
        )


@dataclass
class StatusResult:
    """Response from status endpoint."""
    status: str
    version: str
    public_key: str
    endpoints: Any = field(default_factory=list)
    capabilities: Optional[Dict[str, bool]] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "StatusResult":
        return cls(
            status=data.get("status", ""),
            version=data.get("version", ""),
            public_key=data.get("public_key", ""),
            endpoints=data.get("endpoints", []),
            capabilities=data.get("capabilities"),
        )


# ============================================================================
# P1: Budget Models
# ============================================================================


@dataclass
class BudgetStatusEntry:
    """A single budget type's status."""
    type: str  # 'human' | 'error' | 'model' | 'cost'
    used: float
    limit: float
    remaining: float
    utilization: float
    decision: str  # 'OK' | 'WARN' | 'TIGHTEN' | 'BLOCK'
    window_start: int
    window_end: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetStatusEntry":
        return cls(
            type=data.get("type", ""),
            used=data.get("used", 0.0),
            limit=data.get("limit", 0.0),
            remaining=data.get("remaining", 0.0),
            utilization=data.get("utilization", 0.0),
            decision=data.get("decision", "OK"),
            window_start=data.get("window_start", 0),
            window_end=data.get("window_end", 0),
        )


@dataclass
class BudgetStatusResult:
    """Response from budget status endpoint."""
    budgets: List[BudgetStatusEntry]
    overall_decision: str

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetStatusResult":
        budgets = [BudgetStatusEntry.from_dict(b) for b in data.get("budgets", [])]
        return cls(
            budgets=budgets,
            overall_decision=data.get("overall_decision", "OK"),
        )


@dataclass
class BudgetConsumeResult:
    """Response from budget consume endpoint."""
    success: bool
    remaining: float
    decision: str
    ledger_entry_id: str

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetConsumeResult":
        return cls(
            success=data.get("success", False),
            remaining=data.get("remaining", 0.0),
            decision=data.get("decision", "OK"),
            ledger_entry_id=data.get("ledger_entry_id", ""),
        )


@dataclass
class BudgetHistoryEntry:
    """A single budget ledger entry."""
    id: str
    budget_type: str
    amount: float
    reason: str
    timestamp: int
    balance_after: float

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetHistoryEntry":
        return cls(
            id=data.get("id", ""),
            budget_type=data.get("budget_type", ""),
            amount=data.get("amount", 0.0),
            reason=data.get("reason", ""),
            timestamp=data.get("timestamp", 0),
            balance_after=data.get("balance_after", 0.0),
        )


@dataclass
class BudgetHistoryResult:
    """Response from budget history endpoint."""
    entries: List[BudgetHistoryEntry]
    total: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetHistoryResult":
        entries = [BudgetHistoryEntry.from_dict(e) for e in data.get("entries", [])]
        return cls(entries=entries, total=data.get("total", 0))


@dataclass
class BudgetSetLimitResult:
    """Response from budget set-limit endpoint."""
    success: bool
    budget_type: str
    new_limit: float
    window_hours: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetSetLimitResult":
        return cls(
            success=data.get("success", False),
            budget_type=data.get("budget_type", ""),
            new_limit=data.get("new_limit", 0.0),
            window_hours=data.get("window_hours", 24),
        )


@dataclass
class BudgetAlertEntry:
    """A single budget alert."""
    budget_type: str
    utilization: float
    threshold: float
    message: str

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetAlertEntry":
        return cls(
            budget_type=data.get("budget_type", ""),
            utilization=data.get("utilization", 0.0),
            threshold=data.get("threshold", 0.0),
            message=data.get("message", ""),
        )


@dataclass
class BudgetAlertResult:
    """Response from budget alerts endpoint."""
    alerts: List[BudgetAlertEntry]

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetAlertResult":
        alerts = [BudgetAlertEntry.from_dict(a) for a in data.get("alerts", [])]
        return cls(alerts=alerts)


# ============================================================================
# P1: Audit Models
# ============================================================================


@dataclass
class AuditEntry:
    """A single audit chain record."""
    id: str
    event_type: str
    source: str
    actor: str
    actor_hash: str
    verdict: str
    trust_score: float
    policy_version: str
    decision_id: str
    trace_id: str
    event_hash: str
    prev_hash: str
    chain_index: int
    details: Dict[str, Any]
    created_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditEntry":
        return cls(
            id=data.get("id", ""),
            event_type=data.get("event_type", ""),
            source=data.get("source", ""),
            actor=data.get("actor", ""),
            actor_hash=data.get("actor_hash", ""),
            verdict=data.get("verdict", ""),
            trust_score=data.get("trust_score", 0.0),
            policy_version=data.get("policy_version", ""),
            decision_id=data.get("decision_id", ""),
            trace_id=data.get("trace_id", ""),
            event_hash=data.get("event_hash", ""),
            prev_hash=data.get("prev_hash", ""),
            chain_index=data.get("chain_index", 0),
            details=data.get("details", {}),
            created_at=data.get("created_at", 0),
        )


@dataclass
class AuditTrailResult:
    """Response from audit trail endpoint."""
    records: List[AuditEntry]
    total: int
    chain_valid: bool

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditTrailResult":
        records = [AuditEntry.from_dict(r) for r in data.get("records", [])]
        return cls(
            records=records,
            total=data.get("total", 0),
            chain_valid=data.get("chain_valid", True),
        )


@dataclass
class AuditChainVerifyResult:
    """Response from audit chain verify endpoint."""
    valid: bool
    total_records: int
    verified_records: int
    broken_links: int
    first_break_at: Optional[int] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditChainVerifyResult":
        return cls(
            valid=data.get("valid", True),
            total_records=data.get("total_records", 0),
            verified_records=data.get("verified_records", 0),
            broken_links=data.get("broken_links", 0),
            first_break_at=data.get("first_break_at"),
        )


@dataclass
class AuditStatsResult:
    """Response from audit stats endpoint."""
    total_events: int
    events_today: int
    events_this_week: int
    chain_integrity: float
    top_event_types: List[Dict[str, Any]]
    top_sources: List[Dict[str, Any]]

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditStatsResult":
        return cls(
            total_events=data.get("total_events", 0),
            events_today=data.get("events_today", 0),
            events_this_week=data.get("events_this_week", 0),
            chain_integrity=data.get("chain_integrity", 1.0),
            top_event_types=data.get("top_event_types", []),
            top_sources=data.get("top_sources", []),
        )


@dataclass
class AuditExportResult:
    """Response from audit export endpoint."""
    url: str
    format: str
    record_count: int
    generated_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditExportResult":
        return cls(
            url=data.get("url", ""),
            format=data.get("format", "json"),
            record_count=data.get("record_count", 0),
            generated_at=data.get("generated_at", 0),
        )


# ============================================================================
# P1: Monitoring Models
# ============================================================================


@dataclass
class HealthComponent:
    """A single system component health status."""
    name: str
    status: str  # 'healthy' | 'degraded' | 'unhealthy' | 'unknown'
    latency_ms: float
    last_check: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "HealthComponent":
        return cls(
            name=data.get("name", ""),
            status=data.get("status", "unknown"),
            latency_ms=data.get("latency_ms", 0.0),
            last_check=data.get("last_check", 0),
        )


@dataclass
class SystemHealthResult:
    """Response from system health endpoint."""
    status: str
    uptime_seconds: int
    components: List[HealthComponent]
    version: str

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SystemHealthResult":
        components = [HealthComponent.from_dict(c) for c in data.get("components", [])]
        return cls(
            status=data.get("status", "unknown"),
            uptime_seconds=data.get("uptime_seconds", 0),
            components=components,
            version=data.get("version", ""),
        )


@dataclass
class MetricPoint:
    """A single metric data point."""
    timestamp: int
    value: float
    tags: Optional[Dict[str, str]] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MetricPoint":
        return cls(
            timestamp=data.get("timestamp", 0),
            value=data.get("value", 0.0),
            tags=data.get("tags"),
        )


@dataclass
class MetricsResult:
    """Response from metrics endpoint."""
    name: str
    points: List[MetricPoint]
    total: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MetricsResult":
        points = [MetricPoint.from_dict(p) for p in data.get("points", [])]
        return cls(
            name=data.get("name", ""),
            points=points,
            total=data.get("total", 0),
        )


@dataclass
class MonitoringAlert:
    """A single monitoring alert."""
    id: str
    severity: str  # 'info' | 'warning' | 'error' | 'critical'
    status: str  # 'active' | 'acknowledged' | 'resolved' | 'suppressed'
    title: str
    message: str
    source: str
    created_at: int
    acknowledged_at: Optional[int] = None
    resolved_at: Optional[int] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MonitoringAlert":
        return cls(
            id=data.get("id", ""),
            severity=data.get("severity", "info"),
            status=data.get("status", "active"),
            title=data.get("title", ""),
            message=data.get("message", ""),
            source=data.get("source", ""),
            created_at=data.get("created_at", 0),
            acknowledged_at=data.get("acknowledged_at"),
            resolved_at=data.get("resolved_at"),
        )


@dataclass
class AlertsResult:
    """Response from alerts endpoint."""
    alerts: List[MonitoringAlert]
    total: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AlertsResult":
        alerts = [MonitoringAlert.from_dict(a) for a in data.get("alerts", [])]
        return cls(alerts=alerts, total=data.get("total", 0))


@dataclass
class AlertAckResult:
    """Response from alert acknowledge endpoint."""
    success: bool
    alert_id: str
    acknowledged_at: int

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AlertAckResult":
        return cls(
            success=data.get("success", False),
            alert_id=data.get("alert_id", ""),
            acknowledged_at=data.get("acknowledged_at", 0),
        )


# ============================================================================
# P2: p1p2 Cognitive Security Models
# ============================================================================

@dataclass
class EpistemicCheckResult:
    """Response from epistemic check endpoint."""
    valid: bool
    confidence: float
    violations: List[Dict[str, str]]
    trace_id: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "EpistemicCheckResult":
        return cls(valid=data.get("valid", False), confidence=data.get("confidence", 0.0),
                   violations=data.get("violations", []), trace_id=data.get("trace_id", ""))

@dataclass
class SubmitEvidenceResult:
    """Response from submit evidence endpoint."""
    accepted: bool
    evidence_id: str
    confidence_delta: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SubmitEvidenceResult":
        return cls(accepted=data.get("accepted", False), evidence_id=data.get("evidence_id", ""),
                   confidence_delta=data.get("confidence_delta", 0.0))

@dataclass
class AdversarialDetectResult:
    """Response from adversarial detection endpoint."""
    is_adversarial: bool
    confidence: float
    attack_type: Optional[str]
    indicators: List[str]
    trace_id: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AdversarialDetectResult":
        return cls(is_adversarial=data.get("is_adversarial", False), confidence=data.get("confidence", 0.0),
                   attack_type=data.get("attack_type"), indicators=data.get("indicators", []),
                   trace_id=data.get("trace_id", ""))

@dataclass
class NarrativeFilterResult:
    """Response from narrative filter endpoint."""
    filtered: str
    blocked_items: List[Dict[str, str]]
    rule_count: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "NarrativeFilterResult":
        return cls(filtered=data.get("filtered", ""), blocked_items=data.get("blocked_items", []),
                   rule_count=data.get("rule_count", 0))

@dataclass
class NarrativeRule:
    """A narrative firewall rule."""
    id: str
    pattern: str
    action: str
    enabled: bool
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "NarrativeRule":
        return cls(id=data.get("id", ""), pattern=data.get("pattern", ""),
                   action=data.get("action", ""), enabled=data.get("enabled", False))

@dataclass
class RealityCheckResult:
    """Response from reality check endpoint."""
    anchored: bool
    violations: List[Dict[str, Any]]
    sla_status: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RealityCheckResult":
        return cls(anchored=data.get("anchored", False), violations=data.get("violations", []),
                   sla_status=data.get("sla_status", ""))

@dataclass
class SLAMetricsResult:
    """Response from SLA metrics endpoint."""
    latency_p50: float
    latency_p99: float
    availability: float
    error_rate: float
    period: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SLAMetricsResult":
        return cls(latency_p50=data.get("latency_p50", 0.0), latency_p99=data.get("latency_p99", 0.0),
                   availability=data.get("availability", 0.0), error_rate=data.get("error_rate", 0.0),
                   period=data.get("period", ""))

@dataclass
class ContextBundle:
    """A context bundle entry."""
    bundle_id: str
    data: Dict[str, Any]
    created_at: int
    ttl: int
    hit_count: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ContextBundle":
        return cls(bundle_id=data.get("bundle_id", ""), data=data.get("data", {}),
                   created_at=data.get("created_at", 0), ttl=data.get("ttl", 0),
                   hit_count=data.get("hit_count", 0))

@dataclass
class MemoryWriteResult:
    """Response from memory write endpoint."""
    success: bool
    entry_id: str
    namespace: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MemoryWriteResult":
        return cls(success=data.get("success", False), entry_id=data.get("entry_id", ""),
                   namespace=data.get("namespace", ""))

@dataclass
class MemorySearchResult:
    """Response from memory search endpoint."""
    results: List[Dict[str, Any]]
    total: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MemorySearchResult":
        return cls(results=data.get("results", []), total=data.get("total", 0))

@dataclass
class PrecedentCheckResult:
    """Response from precedent check endpoint."""
    has_precedent: bool
    similar_decisions: List[Dict[str, Any]]
    recommendation: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PrecedentCheckResult":
        return cls(has_precedent=data.get("has_precedent", False),
                   similar_decisions=data.get("similar_decisions", []),
                   recommendation=data.get("recommendation", ""))

@dataclass
class CostEventResult:
    """Response from cost event endpoint."""
    recorded: bool
    event_id: str
    daily_total: float
    budget_remaining: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CostEventResult":
        return cls(recorded=data.get("recorded", False), event_id=data.get("event_id", ""),
                   daily_total=data.get("daily_total", 0.0), budget_remaining=data.get("budget_remaining", 0.0))

@dataclass
class CanaryLogResult:
    """Response from canary log endpoint."""
    logged: bool
    canary_id: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CanaryLogResult":
        return cls(logged=data.get("logged", False), canary_id=data.get("canary_id", ""))

@dataclass
class CanaryReplayResult:
    """Response from canary replay endpoint."""
    original: Dict[str, str]
    replayed: Dict[str, str]
    match: bool
    drift_score: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CanaryReplayResult":
        return cls(original=data.get("original", {}), replayed=data.get("replayed", {}),
                   match=data.get("match", False), drift_score=data.get("drift_score", 0.0))

@dataclass
class DegradationEntry:
    """A degradation entry."""
    id: str
    name: str
    level: str
    status: str
    created_at: int
    resolved_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DegradationEntry":
        return cls(id=data.get("id", ""), name=data.get("name", ""), level=data.get("level", ""),
                   status=data.get("status", ""), created_at=data.get("created_at", 0),
                   resolved_at=data.get("resolved_at"))

@dataclass
class DegradationListResult:
    """Response from degradation list endpoint."""
    degradations: List[DegradationEntry]
    total: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DegradationListResult":
        items = [DegradationEntry.from_dict(d) for d in data.get("degradations", [])]
        return cls(degradations=items, total=data.get("total", 0))

@dataclass
class MetaSupervisionResult:
    """Response from meta supervision endpoint."""
    health_score: float
    anomalies: List[Dict[str, Any]]
    recommendations: List[str]
    last_evaluated: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MetaSupervisionResult":
        return cls(health_score=data.get("health_score", 0.0), anomalies=data.get("anomalies", []),
                   recommendations=data.get("recommendations", []), last_evaluated=data.get("last_evaluated", 0))

@dataclass
class FailureBudgetResult:
    """Response from failure budget endpoint."""
    total_budget: float
    consumed: float
    remaining: float
    utilization: float
    window_hours: int
    recent_failures: List[Dict[str, Any]]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "FailureBudgetResult":
        return cls(total_budget=data.get("total_budget", 0.0), consumed=data.get("consumed", 0.0),
                   remaining=data.get("remaining", 0.0), utilization=data.get("utilization", 0.0),
                   window_hours=data.get("window_hours", 0), recent_failures=data.get("recent_failures", []))

@dataclass
class LLMEvaluationResult:
    """Response from LLM evaluation endpoint."""
    overall_score: float
    checks: List[Dict[str, Any]]
    model_risk: float
    rule_health: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "LLMEvaluationResult":
        return cls(overall_score=data.get("overall_score", 0.0), checks=data.get("checks", []),
                   model_risk=data.get("model_risk", 0.0), rule_health=data.get("rule_health", 0.0))

@dataclass
class ReasoningAnalysisResult:
    """Response from reasoning analysis endpoint."""
    coherence: float
    logical_gaps: List[Dict[str, str]]
    fallacies: List[str]
    overall_quality: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ReasoningAnalysisResult":
        return cls(coherence=data.get("coherence", 0.0), logical_gaps=data.get("logical_gaps", []),
                   fallacies=data.get("fallacies", []), overall_quality=data.get("overall_quality", ""))


# ============================================================================
# P2: p3Fusion Compliance & Governance Models
# ============================================================================

@dataclass
class DataAsset:
    """A data governance asset."""
    id: str
    name: str
    type: str
    classification: str
    owner: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DataAsset":
        return cls(id=data.get("id", ""), name=data.get("name", ""), type=data.get("type", ""),
                   classification=data.get("classification", ""), owner=data.get("owner", ""),
                   created_at=data.get("created_at", 0))

@dataclass
class DataClassifyResult:
    """Response from data classification endpoint."""
    classification: str
    confidence: float
    pii_detected: bool
    categories: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DataClassifyResult":
        return cls(classification=data.get("classification", ""), confidence=data.get("confidence", 0.0),
                   pii_detected=data.get("pii_detected", False), categories=data.get("categories", []))

@dataclass
class DataLineageResult:
    """Response from data lineage endpoint."""
    asset_id: str
    lineage: List[Dict[str, Any]]
    depth: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DataLineageResult":
        return cls(asset_id=data.get("asset_id", ""), lineage=data.get("lineage", []),
                   depth=data.get("depth", 0))

@dataclass
class DataQualityResult:
    """Response from data quality check endpoint."""
    passed: bool
    score: float
    violations: List[Dict[str, str]]
    checked_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DataQualityResult":
        return cls(passed=data.get("passed", False), score=data.get("score", 0.0),
                   violations=data.get("violations", []), checked_at=data.get("checked_at", 0))

@dataclass
class PIIDetectResult:
    """Response from PII detection endpoint."""
    pii_found: bool
    entities: List[Dict[str, Any]]
    risk_level: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PIIDetectResult":
        return cls(pii_found=data.get("pii_found", False), entities=data.get("entities", []),
                   risk_level=data.get("risk_level", ""))

@dataclass
class MaskDataResult:
    """Response from data masking endpoint."""
    masked: str
    entities_masked: int
    rules_applied: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MaskDataResult":
        return cls(masked=data.get("masked", ""), entities_masked=data.get("entities_masked", 0),
                   rules_applied=data.get("rules_applied", []))

@dataclass
class ConsentCheckResult:
    """Response from consent check endpoint."""
    consented: bool
    consent_id: Optional[str] = None
    granted_at: Optional[int] = None
    expires_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ConsentCheckResult":
        return cls(consented=data.get("consented", False), consent_id=data.get("consent_id"),
                   granted_at=data.get("granted_at"), expires_at=data.get("expires_at"))

@dataclass
class PIAEntry:
    """A Privacy Impact Assessment entry."""
    id: str
    name: str
    status: str
    risk_level: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PIAEntry":
        return cls(id=data.get("id", ""), name=data.get("name", ""), status=data.get("status", ""),
                   risk_level=data.get("risk_level", ""), created_at=data.get("created_at", 0))

@dataclass
class ComplianceCheckResult:
    """Response from compliance check endpoint."""
    compliant: bool
    score: float
    controls_passed: int
    controls_failed: int
    findings: List[Dict[str, str]]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ComplianceCheckResult":
        return cls(compliant=data.get("compliant", False), score=data.get("score", 0.0),
                   controls_passed=data.get("controls_passed", 0), controls_failed=data.get("controls_failed", 0),
                   findings=data.get("findings", []))

@dataclass
class ComplianceReportResult:
    """Response from compliance report generation endpoint."""
    report_id: str
    framework: str
    generated_at: int
    summary: str
    download_url: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ComplianceReportResult":
        return cls(report_id=data.get("report_id", ""), framework=data.get("framework", ""),
                   generated_at=data.get("generated_at", 0), summary=data.get("summary", ""),
                   download_url=data.get("download_url"))

@dataclass
class GapAnalysisResult:
    """Response from gap analysis endpoint."""
    total_gaps: int
    gaps: List[Dict[str, str]]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "GapAnalysisResult":
        return cls(total_gaps=data.get("total_gaps", 0), gaps=data.get("gaps", []))

@dataclass
class QuotaCheckResult:
    """Response from quota check endpoint."""
    allowed: bool
    current_usage: float
    limit: float
    utilization: float
    resets_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "QuotaCheckResult":
        return cls(allowed=data.get("allowed", False), current_usage=data.get("current_usage", 0.0),
                   limit=data.get("limit", 0.0), utilization=data.get("utilization", 0.0),
                   resets_at=data.get("resets_at"))

@dataclass
class AccessValidateResult:
    """Response from access validation endpoint."""
    allowed: bool
    reason: Optional[str] = None
    tenant_status: str = ""
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AccessValidateResult":
        return cls(allowed=data.get("allowed", False), reason=data.get("reason"),
                   tenant_status=data.get("tenant_status", ""))

@dataclass
class SubscriptionStatsResult:
    """Response from subscription stats endpoint."""
    total_subscriptions: int
    active: int
    churned: int
    mrr: float
    arr: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SubscriptionStatsResult":
        return cls(total_subscriptions=data.get("total_subscriptions", 0), active=data.get("active", 0),
                   churned=data.get("churned", 0), mrr=data.get("mrr", 0.0), arr=data.get("arr", 0.0))

@dataclass
class TrustScoreResult:
    """Response from trust score calculation endpoint."""
    entity_id: str
    score: float
    grade: str
    factors: List[Dict[str, Any]]
    calculated_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TrustScoreResult":
        return cls(entity_id=data.get("entity_id", ""), score=data.get("score", 0.0),
                   grade=data.get("grade", ""), factors=data.get("factors", []),
                   calculated_at=data.get("calculated_at", 0))

@dataclass
class TrustScoreHistoryResult:
    """Response from trust score history endpoint."""
    entity_id: str
    history: List[Dict[str, Any]]
    trend: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TrustScoreHistoryResult":
        return cls(entity_id=data.get("entity_id", ""), history=data.get("history", []),
                   trend=data.get("trend", ""))

@dataclass
class BatchScoreResult:
    """Response from batch score calculation endpoint."""
    scores: List[Dict[str, Any]]
    calculated_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BatchScoreResult":
        return cls(scores=data.get("scores", []), calculated_at=data.get("calculated_at", 0))

@dataclass
class RiskAssessResult:
    """Response from risk assessment endpoint."""
    risk_level: str
    score: float
    factors: List[Dict[str, str]]
    mitigations: List[str]
    assessed_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RiskAssessResult":
        return cls(risk_level=data.get("risk_level", ""), score=data.get("score", 0.0),
                   factors=data.get("factors", []), mitigations=data.get("mitigations", []),
                   assessed_at=data.get("assessed_at", 0))

@dataclass
class RiskDetectResult:
    """Response from risk detection endpoint."""
    risks: List[Dict[str, Any]]
    total: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RiskDetectResult":
        return cls(risks=data.get("risks", []), total=data.get("total", 0))

@dataclass
class IncidentReportResult:
    """Response from incident report endpoint."""
    incident_id: str
    status: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "IncidentReportResult":
        return cls(incident_id=data.get("incident_id", ""), status=data.get("status", ""),
                   created_at=data.get("created_at", 0))

@dataclass
class IncidentEntry:
    """An incident entry."""
    id: str
    title: str
    severity: str
    status: str
    created_at: int
    resolved_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "IncidentEntry":
        return cls(id=data.get("id", ""), title=data.get("title", ""), severity=data.get("severity", ""),
                   status=data.get("status", ""), created_at=data.get("created_at", 0),
                   resolved_at=data.get("resolved_at"))

@dataclass
class PolicyEntry:
    """A policy entry."""
    id: str
    name: str
    version: str
    status: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PolicyEntry":
        return cls(id=data.get("id", ""), name=data.get("name", ""), version=data.get("version", ""),
                   status=data.get("status", ""), created_at=data.get("created_at", 0))

@dataclass
class CreatePolicyResult:
    """Response from create policy endpoint."""
    policy_id: str
    version: str
    status: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CreatePolicyResult":
        return cls(policy_id=data.get("policy_id", ""), version=data.get("version", ""),
                   status=data.get("status", ""), created_at=data.get("created_at", 0))

@dataclass
class EvaluatePolicyResult:
    """Response from policy evaluation endpoint."""
    allowed: bool
    matched_rules: List[Dict[str, str]]
    policy_version: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "EvaluatePolicyResult":
        return cls(allowed=data.get("allowed", False), matched_rules=data.get("matched_rules", []),
                   policy_version=data.get("policy_version", ""))

@dataclass
class ConflictDetectResult:
    """Response from conflict detection endpoint."""
    conflicts: List[Dict[str, str]]
    total: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ConflictDetectResult":
        return cls(conflicts=data.get("conflicts", []), total=data.get("total", 0))

@dataclass
class IntegrationRule:
    """An integration rule entry."""
    id: str
    name: str
    event_type: str
    action: str
    enabled: bool
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "IntegrationRule":
        return cls(id=data.get("id", ""), name=data.get("name", ""), event_type=data.get("event_type", ""),
                   action=data.get("action", ""), enabled=data.get("enabled", False),
                   created_at=data.get("created_at", 0))

@dataclass
class CreateIntegrationRuleResult:
    """Response from create integration rule endpoint."""
    rule_id: str
    created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CreateIntegrationRuleResult":
        return cls(rule_id=data.get("rule_id", ""), created_at=data.get("created_at", 0))

@dataclass
class PublishEventResult:
    """Response from publish event endpoint."""
    event_id: str
    rules_triggered: int
    published_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PublishEventResult":
        return cls(event_id=data.get("event_id", ""), rules_triggered=data.get("rules_triggered", 0),
                   published_at=data.get("published_at", 0))


# ---- P3 ModelOps models ----

@dataclass
class ModelInfo:
    """Model information."""
    id: str; name: str; provider: str; status: str; latency_p50: float; latency_p99: float; error_rate: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ModelInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), provider=data.get("provider",""),
                   status=data.get("status",""), latency_p50=data.get("latency_p50",0),
                   latency_p99=data.get("latency_p99",0), error_rate=data.get("error_rate",0))

@dataclass
class ModelSelectResult:
    """Model selection result."""
    model_id: str; reason: str; fallback: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ModelSelectResult":
        return cls(model_id=data.get("model_id",""), reason=data.get("reason",""), fallback=data.get("fallback"))

@dataclass
class CircuitBreakerEvent:
    """Circuit breaker event."""
    model_id: str; event_type: str; timestamp: int; details: Dict[str, Any]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CircuitBreakerEvent":
        return cls(model_id=data.get("model_id",""), event_type=data.get("event_type",""),
                   timestamp=data.get("timestamp",0), details=data.get("details",{}))

@dataclass
class ABTestInfo:
    """A/B test information."""
    id: str; task_type: str; variants: List[Dict[str, Any]]; status: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ABTestInfo":
        return cls(id=data.get("id",""), task_type=data.get("task_type",""),
                   variants=data.get("variants",[]), status=data.get("status",""))

@dataclass
class PromptTemplateInfo:
    """Prompt template information."""
    id: str; name: str; version: str; template: str; system_prompt: Optional[str]; variables: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PromptTemplateInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), version=data.get("version",""),
                   template=data.get("template",""), system_prompt=data.get("system_prompt"),
                   variables=data.get("variables",[]))

@dataclass
class PromptRenderResult:
    """Prompt render result."""
    rendered: str; template_id: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PromptRenderResult":
        return cls(rendered=data.get("rendered",""), template_id=data.get("template_id",""))

@dataclass
class RoutingDecisionInfo:
    """Routing decision log entry."""
    id: str; model_id: str; reason: str; timestamp: int; latency_ms: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RoutingDecisionInfo":
        return cls(id=data.get("id",""), model_id=data.get("model_id",""), reason=data.get("reason",""),
                   timestamp=data.get("timestamp",0), latency_ms=data.get("latency_ms",0))

@dataclass
class ModelUsageStatsInfo:
    """Model usage statistics."""
    model_id: str; total_calls: int; avg_latency: float; error_count: int; period: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ModelUsageStatsInfo":
        return cls(model_id=data.get("model_id",""), total_calls=data.get("total_calls",0),
                   avg_latency=data.get("avg_latency",0), error_count=data.get("error_count",0),
                   period=data.get("period",""))

@dataclass
class ModelHealthStatusInfo:
    """Model health status."""
    model_id: str; status: str; uptime: float; last_check: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ModelHealthStatusInfo":
        return cls(model_id=data.get("model_id",""), status=data.get("status",""),
                   uptime=data.get("uptime",0), last_check=data.get("last_check",0))

# ---- P3 TaskQueue models ----

@dataclass
class TaskInfo:
    """Task information."""
    id: str; type: str; status: str; priority: int; payload: Dict[str, Any]; created_at: int; updated_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TaskInfo":
        return cls(id=data.get("id",""), type=data.get("type",""), status=data.get("status",""),
                   priority=data.get("priority",0), payload=data.get("payload",{}),
                   created_at=data.get("created_at",0), updated_at=data.get("updated_at",0))

@dataclass
class TaskQueueStatsInfo:
    """Task queue statistics."""
    pending: int; running: int; completed: int; failed: int; dead_letter: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TaskQueueStatsInfo":
        return cls(pending=data.get("pending",0), running=data.get("running",0),
                   completed=data.get("completed",0), failed=data.get("failed",0),
                   dead_letter=data.get("dead_letter",0))

# ---- P3 Experiment models ----

@dataclass
class ExperimentInfo:
    """Experiment information."""
    id: str; name: str; status: str; variants: List[Dict[str, Any]]; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ExperimentInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), status=data.get("status",""),
                   variants=data.get("variants",[]), created_at=data.get("created_at",0))

@dataclass
class ExperimentAssignment:
    """Experiment assignment result."""
    experiment_id: str; variant: str; user_id: str; assigned_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ExperimentAssignment":
        return cls(experiment_id=data.get("experiment_id",""), variant=data.get("variant",""),
                   user_id=data.get("user_id",""), assigned_at=data.get("assigned_at",0))

# ---- P3 AuditRegression models ----

@dataclass
class RegressionSuite:
    """Regression test suite."""
    id: str; name: str; description: Optional[str]; test_count: int; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RegressionSuite":
        return cls(id=data.get("id",""), name=data.get("name",""), description=data.get("description"),
                   test_count=data.get("test_count",0), created_at=data.get("created_at",0))

@dataclass
class RegressionRun:
    """Regression test run result."""
    id: str; suite_id: str; status: str; passed: int; failed: int; total: int; started_at: int; completed_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RegressionRun":
        return cls(id=data.get("id",""), suite_id=data.get("suite_id",""), status=data.get("status",""),
                   passed=data.get("passed",0), failed=data.get("failed",0), total=data.get("total",0),
                   started_at=data.get("started_at",0), completed_at=data.get("completed_at"))

# ---- P3 AuditReplay models ----

@dataclass
class SnapshotInfo:
    """Audit snapshot."""
    id: str; snapshot_type: str; entity_type: str; entity_id: str; snapshot_data: Dict[str, Any]; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SnapshotInfo":
        return cls(id=data.get("id",""), snapshot_type=data.get("snapshot_type",""),
                   entity_type=data.get("entity_type",""), entity_id=data.get("entity_id",""),
                   snapshot_data=data.get("snapshot_data",{}), created_at=data.get("created_at",0))

@dataclass
class ReplaySessionInfo:
    """Replay session."""
    id: str; name: str; session_type: str; status: str; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ReplaySessionInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), session_type=data.get("session_type",""),
                   status=data.get("status",""), created_at=data.get("created_at",0))

@dataclass
class SnapshotCompareResult:
    """Snapshot comparison result."""
    snapshot_a: str; snapshot_b: str; diffs: List[Dict[str, Any]]; total_changes: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SnapshotCompareResult":
        return cls(snapshot_a=data.get("snapshot_a",""), snapshot_b=data.get("snapshot_b",""),
                   diffs=data.get("diffs",[]), total_changes=data.get("total_changes",0))


# ============================================================================
# P4: Extended models for Gate/Approval/Audit/KillSwitch/TrustBundle/Policy/
#     RBAC/Budget/DefaultDeny/Metering/Monitoring/Experiment/Integration/
#     TaskQueue/OpenGuard
# ============================================================================

@dataclass
class GateConfigResult:
    """Gate configuration."""
    kill_switch_enabled: bool; default_deny: bool; risk_threshold: float; require_approval_above: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "GateConfigResult":
        return cls(kill_switch_enabled=data.get("kill_switch_enabled", False), default_deny=data.get("default_deny", False),
                   risk_threshold=data.get("risk_threshold", 0), require_approval_above=data.get("require_approval_above", 0))

@dataclass
class HighRiskActionInfo:
    """High risk action."""
    action: str; resource: str; risk_score: float; last_seen: int; count: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "HighRiskActionInfo":
        return cls(action=data.get("action",""), resource=data.get("resource",""),
                   risk_score=data.get("risk_score",0), last_seen=data.get("last_seen",0), count=data.get("count",0))

@dataclass
class PendingApprovalInfo:
    """Pending approval."""
    id: str; decision_id: str; action: str; resource: str; urgency: str; requested_at: int; justification: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PendingApprovalInfo":
        return cls(id=data.get("id",""), decision_id=data.get("decision_id",""), action=data.get("action",""),
                   resource=data.get("resource",""), urgency=data.get("urgency",""),
                   requested_at=data.get("requested_at",0), justification=data.get("justification"))

@dataclass
class ApprovalDetailInfo:
    """Approval detail."""
    id: str; decision_id: str; action: str; resource: str; status: str; requested_at: int; resolved_at: Optional[int] = None; resolver: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApprovalDetailInfo":
        return cls(id=data.get("id",""), decision_id=data.get("decision_id",""), action=data.get("action",""),
                   resource=data.get("resource",""), status=data.get("status",""),
                   requested_at=data.get("requested_at",0), resolved_at=data.get("resolved_at"), resolver=data.get("resolver"))

@dataclass
class ApprovalStatsInfo:
    """Approval statistics."""
    total: int; pending: int; approved: int; rejected: int; avg_resolution_time_ms: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApprovalStatsInfo":
        return cls(total=data.get("total",0), pending=data.get("pending",0), approved=data.get("approved",0),
                   rejected=data.get("rejected",0), avg_resolution_time_ms=data.get("avg_resolution_time_ms",0))

@dataclass
class AuditChainResult:
    """Audit chain."""
    entries: List[Dict[str, Any]]; valid: bool
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditChainResult":
        return cls(entries=data.get("entries",[]), valid=data.get("valid",False))

@dataclass
class AuditDetailResult:
    """Audit detail."""
    id: str; event_type: str; actor: str; action: str; resource: str; timestamp: int; metadata: Dict[str, Any]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AuditDetailResult":
        return cls(id=data.get("id",""), event_type=data.get("event_type",""), actor=data.get("actor",""),
                   action=data.get("action",""), resource=data.get("resource",""),
                   timestamp=data.get("timestamp",0), metadata=data.get("metadata",{}))

@dataclass
class DailyRootVerifyResult:
    """Daily root verification."""
    date: str; root_hash: str; entry_count: int; valid: bool
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DailyRootVerifyResult":
        return cls(date=data.get("date",""), root_hash=data.get("root_hash",""),
                   entry_count=data.get("entry_count",0), valid=data.get("valid",False))

@dataclass
class DegradationStateResult:
    """Kill switch degradation state."""
    level: str; reason: Optional[str] = None; activated_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DegradationStateResult":
        return cls(level=data.get("level",""), reason=data.get("reason"), activated_at=data.get("activated_at"))

@dataclass
class KillSwitchOperationCheck:
    """Kill switch operation check."""
    allowed: bool; reason: Optional[str] = None; degradation_level: str = ""
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "KillSwitchOperationCheck":
        return cls(allowed=data.get("allowed",False), reason=data.get("reason"),
                   degradation_level=data.get("degradation_level",""))

@dataclass
class TrustChainVerifyResult:
    """Trust chain verification."""
    valid: bool; chain_length: int; broken_links: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TrustChainVerifyResult":
        return cls(valid=data.get("valid",False), chain_length=data.get("chain_length",0),
                   broken_links=data.get("broken_links",[]))

@dataclass
class EvidenceWriteResult:
    """Evidence write result."""
    evidence_id: str; hash: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "EvidenceWriteResult":
        return cls(evidence_id=data.get("evidence_id",""), hash=data.get("hash",""))

@dataclass
class PolicyCompileResult:
    """Policy compile result."""
    compiled: bool; errors: List[str]; warnings: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PolicyCompileResult":
        return cls(compiled=data.get("compiled",False), errors=data.get("errors",[]), warnings=data.get("warnings",[]))

@dataclass
class PolicyVersionInfo:
    """Policy version."""
    id: str; policy_id: str; version: int; rules: Dict[str, Any]; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PolicyVersionInfo":
        return cls(id=data.get("id",""), policy_id=data.get("policy_id",""), version=data.get("version",0),
                   rules=data.get("rules",{}), created_at=data.get("created_at",0))

@dataclass
class PermissionCheckResult:
    """Permission check result."""
    allowed: bool; reason: Optional[str] = None; matched_role: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "PermissionCheckResult":
        return cls(allowed=data.get("allowed",False), reason=data.get("reason"), matched_role=data.get("matched_role"))

@dataclass
class RolePermissionsResult:
    """Role permissions."""
    role: str; permissions: List[str]; inherited_from: Optional[List[str]] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "RolePermissionsResult":
        return cls(role=data.get("role",""), permissions=data.get("permissions",[]),
                   inherited_from=data.get("inherited_from"))

@dataclass
class DualApprovalCheckResult:
    """Dual approval check."""
    required: bool; reason: Optional[str] = None; approvers_needed: int = 0
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DualApprovalCheckResult":
        return cls(required=data.get("required",False), reason=data.get("reason"),
                   approvers_needed=data.get("approvers_needed",0))

@dataclass
class ApprovalIsolationResult:
    """Approval isolation check."""
    isolated: bool; conflicts: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApprovalIsolationResult":
        return cls(isolated=data.get("isolated",False), conflicts=data.get("conflicts",[]))

@dataclass
class BudgetStatusResult:
    """Budget status."""
    budget_id: str; limit: float; consumed: float; remaining: float; period: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetStatusResult":
        return cls(budget_id=data.get("budget_id",""), limit=data.get("limit",0), consumed=data.get("consumed",0),
                   remaining=data.get("remaining",0), period=data.get("period",""))

@dataclass
class BudgetProceedResult:
    """Budget proceed check."""
    can_proceed: bool; reason: Optional[str] = None; remaining: float = 0
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetProceedResult":
        return cls(can_proceed=data.get("can_proceed",False), reason=data.get("reason"),
                   remaining=data.get("remaining",0))

@dataclass
class BudgetHumanCheckResult:
    """Budget human check."""
    requires_human: bool; reason: Optional[str] = None; threshold: float = 0
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BudgetHumanCheckResult":
        return cls(requires_human=data.get("requires_human",False), reason=data.get("reason"),
                   threshold=data.get("threshold",0))

@dataclass
class DefaultDenyOpResult:
    """Default deny operation check."""
    allowed: bool; reason: Optional[str] = None; matched_rule: Optional[str] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DefaultDenyOpResult":
        return cls(allowed=data.get("allowed",False), reason=data.get("reason"), matched_rule=data.get("matched_rule"))

@dataclass
class DefaultDenyAutoAdjustResult:
    """Default deny auto adjust."""
    adjusted: bool; new_rules: List[str]; reason: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DefaultDenyAutoAdjustResult":
        return cls(adjusted=data.get("adjusted",False), new_rules=data.get("new_rules",[]), reason=data.get("reason",""))

@dataclass
class KnownActionInfo:
    """Known action."""
    action: str; resource: str; frequency: int; last_seen: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "KnownActionInfo":
        return cls(action=data.get("action",""), resource=data.get("resource",""),
                   frequency=data.get("frequency",0), last_seen=data.get("last_seen",0))

@dataclass
class MeteringUsageResult:
    """Metering usage stats."""
    total_calls: int; by_action: Dict[str, int]; period: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MeteringUsageResult":
        return cls(total_calls=data.get("total_calls",0), by_action=data.get("by_action",{}), period=data.get("period",""))

@dataclass
class MeteringQuotaResult:
    """Metering quota status."""
    quota: int; used: int; remaining: int; reset_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MeteringQuotaResult":
        return cls(quota=data.get("quota",0), used=data.get("used",0), remaining=data.get("remaining",0), reset_at=data.get("reset_at",0))

@dataclass
class MeteringDailyResult:
    """Metering daily stats."""
    date: str; total: int; allowed: int; blocked: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MeteringDailyResult":
        return cls(date=data.get("date",""), total=data.get("total",0), allowed=data.get("allowed",0), blocked=data.get("blocked",0))

@dataclass
class MeteringSubscriptionResult:
    """Metering subscription."""
    plan: str; status: str; features: List[str]; limits: Dict[str, int]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MeteringSubscriptionResult":
        return cls(plan=data.get("plan",""), status=data.get("status",""), features=data.get("features",[]), limits=data.get("limits",{}))

@dataclass
class AlertRuleInfo:
    """Alert rule."""
    id: str; name: str; condition: str; severity: str; enabled: bool
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AlertRuleInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), condition=data.get("condition",""),
                   severity=data.get("severity",""), enabled=data.get("enabled",False))

@dataclass
class MetricHistoryResult:
    """Metric history."""
    metric: str; data_points: List[Dict[str, Any]]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "MetricHistoryResult":
        return cls(metric=data.get("metric",""), data_points=data.get("data_points",[]))

@dataclass
class FeatureFlagInfo:
    """Feature flag."""
    id: str; name: str; enabled: bool; rollout_percentage: float
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "FeatureFlagInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), enabled=data.get("enabled",False),
                   rollout_percentage=data.get("rollout_percentage",0))

@dataclass
class CanaryDeploymentInfo:
    """Canary deployment."""
    id: str; name: str; status: str; traffic_percentage: float; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CanaryDeploymentInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), status=data.get("status",""),
                   traffic_percentage=data.get("traffic_percentage",0), created_at=data.get("created_at",0))

@dataclass
class ApiKeyInfo:
    """API key info."""
    id: str; name: str; key_prefix: str; scopes: List[str]; created_at: int; expires_at: Optional[int] = None
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApiKeyInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), key_prefix=data.get("key_prefix",""),
                   scopes=data.get("scopes",[]), created_at=data.get("created_at",0), expires_at=data.get("expires_at"))

@dataclass
class ApiKeyUsageResult:
    """API key usage stats."""
    key_id: str; total_calls: int; last_used: int; by_endpoint: Dict[str, int]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApiKeyUsageResult":
        return cls(key_id=data.get("key_id",""), total_calls=data.get("total_calls",0),
                   last_used=data.get("last_used",0), by_endpoint=data.get("by_endpoint",{}))

@dataclass
class WebhookInfo:
    """Webhook info."""
    id: str; url: str; events: List[str]; status: str; created_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "WebhookInfo":
        return cls(id=data.get("id",""), url=data.get("url",""), events=data.get("events",[]),
                   status=data.get("status",""), created_at=data.get("created_at",0))

@dataclass
class IntegrationListItem:
    """Integration list item."""
    id: str; name: str; type: str; status: str; config: Dict[str, Any]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "IntegrationListItem":
        return cls(id=data.get("id",""), name=data.get("name",""), type=data.get("type",""),
                   status=data.get("status",""), config=data.get("config",{}))

@dataclass
class TaskQueueStatsResult:
    """Task queue stats."""
    total: int; pending: int; running: int; completed: int; failed: int; dead_letter: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "TaskQueueStatsResult":
        return cls(total=data.get("total",0), pending=data.get("pending",0), running=data.get("running",0),
                   completed=data.get("completed",0), failed=data.get("failed",0), dead_letter=data.get("dead_letter",0))

@dataclass
class DeadLetterItemInfo:
    """Dead letter item."""
    id: str; task_type: str; error: str; failed_at: int; retry_count: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DeadLetterItemInfo":
        return cls(id=data.get("id",""), task_type=data.get("task_type",""), error=data.get("error",""),
                   failed_at=data.get("failed_at",0), retry_count=data.get("retry_count",0))

@dataclass
class ScanLogInfo:
    """Scan log entry."""
    id: str; input_hash: str; verdict: str; risk_score: float; source: str; scanned_at: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ScanLogInfo":
        return cls(id=data.get("id",""), input_hash=data.get("input_hash",""), verdict=data.get("verdict",""),
                   risk_score=data.get("risk_score",0), source=data.get("source",""), scanned_at=data.get("scanned_at",0))

@dataclass
class ScanStatsResult:
    """Scan stats."""
    total: int; pass_count: int; warn: int; block: int; by_category: Dict[str, int]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ScanStatsResult":
        return cls(total=data.get("total",0), pass_count=data.get("pass",0), warn=data.get("warn",0),
                   block=data.get("block",0), by_category=data.get("by_category",{}))

@dataclass
class ContentPatternInfo:
    """Content pattern."""
    id: str; name: str; description: str; category: str; severity: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ContentPatternInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), description=data.get("description",""),
                   category=data.get("category",""), severity=data.get("severity",""))

@dataclass
class CustomPatternInfo:
    """Custom pattern."""
    id: str; name: str; pattern: str; category: str; severity: str; is_active: bool; created_by: str
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "CustomPatternInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), pattern=data.get("pattern",""),
                   category=data.get("category",""), severity=data.get("severity",""),
                   is_active=data.get("is_active",False), created_by=data.get("created_by",""))

@dataclass
class GeoStatsResult:
    """Geo stats."""
    by_country: List[Dict[str, Any]]; total: int
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "GeoStatsResult":
        return cls(by_country=data.get("by_country",[]), total=data.get("total",0))

@dataclass
class SemanticModelInfo:
    """Semantic model."""
    id: str; name: str; description: str; capabilities: List[str]
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "SemanticModelInfo":
        return cls(id=data.get("id",""), name=data.get("name",""), description=data.get("description",""),
                   capabilities=data.get("capabilities",[]))
