"""
Activities for logging user-facing status events.
"""

import base64
import json
import logging
from datetime import datetime

import httpx
from temporalio import activity

from optovia_workflows.types import LogKycEventInput, LogKycEventResult

from ..config import settings

logger = logging.getLogger(__name__)


def _surreal_headers() -> dict[str, str]:
    headers = {
        "Content-Type": "text/plain",
        "Accept": "application/json",
        "NS": settings.SURREALDB_NS,
        "DB": settings.SURREALDB_DB,
    }

    if settings.SURREALDB_USER and settings.SURREALDB_PASS:
        token = base64.b64encode(
            f"{settings.SURREALDB_USER}:{settings.SURREALDB_PASS}".encode("utf-8")
        ).decode("utf-8")
        headers["Authorization"] = f"Basic {token}"

    return headers


@activity.defn(name="log_kyc_event")
def log_kyc_event(data: LogKycEventInput) -> LogKycEventResult:
    """
    Write KYC status event into SurrealDB.

    This activity is best-effort and should not block workflow execution.
    """
    if not settings.SURREALDB_URL:
        logger.warning("SURREALDB_URL is not set; skipping KYC event log")
        return LogKycEventResult(success=False, message="SURREALDB_URL is not set")

    payload = {
        "kyc_id": data.kyc_id,
        "user_id": data.user_id,
        "event": data.event,
        "description": data.description,
        "created_at": datetime.utcnow().isoformat() + "Z",
    }
    query = f"CREATE kyc_event CONTENT {json.dumps(payload)};"

    try:
        with httpx.Client(timeout=settings.SURREALDB_TIMEOUT) as client:
            response = client.post(
                f"{settings.SURREALDB_URL.rstrip('/')}/sql",
                content=query,
                headers=_surreal_headers(),
            )
            response.raise_for_status()
        return LogKycEventResult(success=True, message="Event logged")
    except Exception as exc:
        logger.error("Failed to log KYC event: %s", exc)
        return LogKycEventResult(success=False, message=str(exc))
