"""Data models for the sync engine."""
from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum


class SyncOperation(str, Enum):
    """Types of sync operations."""
    UPSERT = "upsert"
    DELETE = "delete"


@dataclass
class SyncLogEntry:
    """A single change recorded in the _sync_log table."""
    table_name: str
    row_id: str
    operation: SyncOperation
    sync_version: int
    node_id: str
    created_at: str = ""

    @classmethod
    def from_row(cls, row: dict) -> SyncLogEntry:
        return cls(
            table_name=row["table_name"],
            row_id=row["row_id"],
            operation=SyncOperation(row["operation"]),
            sync_version=row["sync_version"],
            node_id=row["node_id"],
            created_at=row.get("created_at", ""),
        )


@dataclass
class SyncState:
    """Current sync state for a node."""
    node_id: str
    sync_version: int
    last_sync_at: str = ""


@dataclass
class SyncBatch:
    """A batch of rows to sync to/from a peer."""
    table_name: str
    rows: list[dict] = field(default_factory=list)
    operations: list[SyncLogEntry] = field(default_factory=list)

    @property
    def size(self) -> int:
        return len(self.rows)


@dataclass
class SyncResult:
    """Result of a sync operation."""
    tables_synced: int = 0
    rows_pushed: int = 0
    rows_pulled: int = 0
    conflicts_resolved: int = 0
    errors: list[str] = field(default_factory=list)

    @property
    def success(self) -> bool:
        return len(self.errors) == 0
