"""External service converters: webhooks, sync, entity, metrics."""

from __future__ import annotations

from noteflow.domain.entities import SyncRun
from noteflow.domain.entities.named_entity import NamedEntity
from noteflow.domain.webhooks.events import WebhookConfig, WebhookDelivery
from noteflow.infrastructure.metrics import PerformanceMetrics

from ...proto import noteflow_pb2

# -----------------------------------------------------------------------------
# Entity Converters
# -----------------------------------------------------------------------------


def entity_to_proto(entity: NamedEntity) -> noteflow_pb2.ExtractedEntity:
    """Convert domain NamedEntity to proto ExtractedEntity.

    Args:
        entity: NamedEntity domain object.

    Returns:
        Proto ExtractedEntity message.
    """
    return noteflow_pb2.ExtractedEntity(
        id=str(entity.id),
        text=entity.text,
        category=entity.category.value,
        segment_ids=list(entity.segment_ids),
        confidence=entity.confidence,
        is_pinned=entity.is_pinned,
    )


# -----------------------------------------------------------------------------
# Webhook Converters
# -----------------------------------------------------------------------------


def webhook_config_to_proto(config: WebhookConfig) -> noteflow_pb2.WebhookConfigProto:
    """Convert domain WebhookConfig to proto message."""
    return noteflow_pb2.WebhookConfigProto(
        id=str(config.id),
        workspace_id=str(config.workspace_id),
        name=config.name,
        url=config.url,
        events=[e.value for e in config.events],
        enabled=config.enabled,
        timeout_ms=config.timeout_ms,
        max_retries=config.max_retries,
        created_at=int(config.created_at.timestamp()),
        updated_at=int(config.updated_at.timestamp()),
    )


def webhook_delivery_to_proto(
    delivery: WebhookDelivery,
) -> noteflow_pb2.WebhookDeliveryProto:
    """Convert domain WebhookDelivery to proto message."""
    return noteflow_pb2.WebhookDeliveryProto(
        id=str(delivery.id),
        webhook_id=str(delivery.webhook_id),
        event_type=delivery.event_type.value,
        status_code=delivery.status_code or 0,
        error_message=delivery.error_message or "",
        attempt_count=delivery.attempt_count,
        duration_ms=delivery.duration_ms or 0,
        delivered_at=int(delivery.delivered_at.timestamp()),
        succeeded=delivery.succeeded,
    )


# -----------------------------------------------------------------------------
# Sync Converters
# -----------------------------------------------------------------------------


def sync_run_to_proto(run: SyncRun) -> noteflow_pb2.SyncRunProto:
    """Convert a SyncRun domain entity to protobuf message."""
    return noteflow_pb2.SyncRunProto(
        id=str(run.id),
        integration_id=str(run.integration_id),
        status=run.status.value,
        items_synced=run.items_synced,
        error_message=run.error_message or "",
        duration_ms=run.duration_ms or 0,
        started_at=run.started_at.isoformat(),
        completed_at=run.ended_at.isoformat() if run.ended_at else "",
    )


# -----------------------------------------------------------------------------
# Observability Converters
# -----------------------------------------------------------------------------


def metrics_to_proto(
    metrics: PerformanceMetrics,
) -> noteflow_pb2.PerformanceMetricsPoint:
    """Convert metrics to proto message."""
    return noteflow_pb2.PerformanceMetricsPoint(
        timestamp=metrics.timestamp,
        cpu_percent=metrics.cpu_percent,
        memory_percent=metrics.memory_percent,
        memory_mb=metrics.memory_mb,
        disk_percent=metrics.disk_percent,
        network_bytes_sent=metrics.network_bytes_sent,
        network_bytes_recv=metrics.network_bytes_recv,
        process_memory_mb=metrics.process_memory_mb,
        active_connections=metrics.active_connections,
    )
