"""Activities for TerminusDB document storage."""
import base64
import logging
import httpx
from temporalio import activity

from optovia_workflows.types import SaveOfferDescriptionInput, SaveOfferDescriptionResult
from ..config import settings

logger = logging.getLogger(__name__)


def _basic_auth_header() -> str:
    if settings.TERMINUS_BASIC_USER and settings.TERMINUS_BASIC_PASS:
        token = f"{settings.TERMINUS_BASIC_USER}:{settings.TERMINUS_BASIC_PASS}".encode("utf-8")
        return "Basic " + base64.b64encode(token).decode("utf-8")
    return ""


@activity.defn(name="save_offer_description")
def save_offer_description(data: SaveOfferDescriptionInput) -> SaveOfferDescriptionResult:
    if not settings.TERMINUS_DOCUMENT_URL:
        return SaveOfferDescriptionResult(success=False, message="Terminus URL not configured")

    headers = {"Content-Type": "application/json"}
    auth_header = _basic_auth_header()
    if auth_header:
        headers["Authorization"] = auth_header

    # Document ID must be prefixed with schema type: {SchemaType}/{uuid}
    document_id = f"{data.schema_id}/{data.offer_uuid}"
    document = {
        "@type": data.schema_id,
        "@id": document_id,
        **data.payload,
    }

    try:
        with httpx.Client(timeout=settings.TERMINUS_TIMEOUT) as client:
            response = client.post(
                settings.TERMINUS_DOCUMENT_URL,
                json=document,
                headers=headers,
                params={
                    "graph_type": "instance",
                    "author": "platform-worker",
                    "message": f"Create offer {data.offer_uuid}",
                },
            )
            response.raise_for_status()
        return SaveOfferDescriptionResult(success=True, document_id=data.offer_uuid)
    except Exception as exc:
        logger.exception("Failed to save offer description to Terminus")
        return SaveOfferDescriptionResult(success=False, message=str(exc))
