"""GoldHold types. Patent Pending. All Auto Tunes LLC. U.S. #63/988,484."""

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


STORAGE_CLASSES = ("canonical", "corrections", "working", "archive")

PACKET_TYPES = (
    "FACT", "DECISION", "DIRECTIVE", "NOTE", "CORRECTION", "CHECKPOINT",
    "IDENTITY", "CREDENTIAL", "DOCUMENT", "RELATION", "ASSET_REF",
    "TOMBSTONE", "MANIFEST", "CUSTOM",
)

STATUS_LIFECYCLE = ("active", "provisional", "superseded", "revoked", "archived")


@dataclass
class Memory:
    packet_id: str = ""
    subject: str = ""
    body: str = ""
    type: str = "NOTE"
    confidence: str = "medium"
    class_: str = "working"
    status: str = "active"
    created_at: str = ""
    score: float = 0.0

    @classmethod
    def from_dict(cls, d):
        if not isinstance(d, dict):
            return cls(body=str(d))
        return cls(
            packet_id=d.get("packet_id", ""),
            subject=d.get("subject", ""),
            body=d.get("body", ""),
            type=d.get("type", "NOTE"),
            confidence=d.get("confidence", "medium"),
            class_=d.get("class", d.get("class_", "working")),
            status=d.get("status", "active"),
            created_at=d.get("created_at", ""),
            score=d.get("score", 0.0),
        )


@dataclass
class StoreResult:
    packet_id: str = ""
    chain_position: int = 0
    class_: str = "working"
    status: str = "active"
    dedup: bool = False
    superseded: List[str] = field(default_factory=list)

    @classmethod
    def from_dict(cls, d):
        return cls(
            packet_id=d.get("packet_id", ""),
            chain_position=d.get("chain_position", 0),
            class_=d.get("class", d.get("class_", "working")),
            status=d.get("status", "active"),
            dedup=d.get("dedup", False),
            superseded=d.get("superseded", []),
        )


@dataclass
class TurnResponse:
    ok: bool = False
    stored: List[StoreResult] = field(default_factory=list)
    search_results: List[Memory] = field(default_factory=list)
    _meta: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, d):
        stored_raw = d.get("stored", [])
        if isinstance(stored_raw, list):
            stored = [StoreResult.from_dict(s) for s in stored_raw]
        elif isinstance(stored_raw, dict):
            stored = [StoreResult.from_dict(stored_raw)]
        else:
            stored = []
        results_raw = d.get("search_results", d.get("results", []))
        results = [Memory.from_dict(m) for m in results_raw] if isinstance(results_raw, list) else []
        return cls(ok=d.get("ok", False), stored=stored, search_results=results, _meta=d.get("_meta", {}))


@dataclass
class SessionContext:
    last_session_summary: Optional[str] = None
    active_directives: List[Any] = field(default_factory=list)
    pending_tasks: List[Any] = field(default_factory=list)
    recent_corrections: List[Any] = field(default_factory=list)
    unread_messages: int = 0
    unread_preview: List[Any] = field(default_factory=list)

    @classmethod
    def from_dict(cls, d):
        if not isinstance(d, dict):
            return cls()
        return cls(
            last_session_summary=d.get("last_session_summary"),
            active_directives=d.get("active_directives", []),
            pending_tasks=d.get("pending_tasks", []),
            recent_corrections=d.get("recent_corrections", []),
            unread_messages=d.get("unread_messages", 0),
            unread_preview=d.get("unread_preview", []),
        )


@dataclass
class AutoResponse:
    ok: bool = False
    capability_card: Dict[str, Any] = field(default_factory=dict)
    context: Optional[SessionContext] = None
    _meta: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, d):
        ctx = SessionContext.from_dict(d.get("context", {}))
        return cls(ok=d.get("ok", False), capability_card=d.get("capability_card", {}), context=ctx, _meta=d.get("_meta", {}))


@dataclass
class BatchResponse:
    ok: bool = False
    results: List[Dict[str, Any]] = field(default_factory=list)
    _meta: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, d):
        return cls(ok=d.get("ok", False), results=d.get("results", []), _meta=d.get("_meta", {}))


@dataclass
class CloseResponse:
    ok: bool = False
    _meta: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, d):
        return cls(ok=d.get("ok", False), _meta=d.get("_meta", {}))


@dataclass
class StatusResponse:
    ok: bool = False
    namespace: str = ""
    protocol: str = ""
    message_count: int = 0
    total_vectors: int = 0
    agent_count: int = 0
    your_agent: str = ""
    your_trust: str = ""
    your_rate: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, d):
        return cls(
            ok=d.get("ok", False),
            namespace=d.get("namespace", ""),
            protocol=d.get("protocol", ""),
            message_count=d.get("message_count", 0),
            total_vectors=d.get("total_vectors", 0),
            agent_count=d.get("agent_count", 0),
            your_agent=d.get("your_agent", ""),
            your_trust=d.get("your_trust", ""),
            your_rate=d.get("your_rate", {}),
        )
