import asyncio
import logging
import os
from typing import Tuple

from temporalio.client import Client

logger = logging.getLogger(__name__)

TEMPORAL_INTERNAL_URL = os.getenv("TEMPORAL_INTERNAL_URL", "temporal:7233")
TEMPORAL_NAMESPACE = os.getenv("TEMPORAL_NAMESPACE", "default")
TEMPORAL_TASK_QUEUE = os.getenv("TEMPORAL_TASK_QUEUE", "platform-worker")


async def _start_offer_workflow_async(payload: dict) -> Tuple[str, str]:
    client = await Client.connect(TEMPORAL_INTERNAL_URL, namespace=TEMPORAL_NAMESPACE)

    workflow_id = f"offer-{payload['offer_uuid']}"

    handle = await client.start_workflow(
        "create_offer",
        payload,
        id=workflow_id,
        task_queue=TEMPORAL_TASK_QUEUE,
    )

    logger.info("Started offer workflow %s", workflow_id)
    return handle.id, handle.result_run_id


def start_offer_workflow(
    *,
    offer_uuid: str,
    team_uuid: str,
    product_uuid: str,
    product_name: str,
    category_name: str | None = None,
    location_uuid: str | None = None,
    location_name: str | None = None,
    location_country: str | None = None,
    location_country_code: str | None = None,
    location_latitude: float | None = None,
    location_longitude: float | None = None,
    quantity=None,
    unit: str | None = None,
    price_per_unit=None,
    currency: str | None = None,
    description: str | None = None,
    valid_until=None,
    terminus_schema_id: str | None = None,
    terminus_payload: dict | None = None,
) -> Tuple[str, str]:
    payload = {
        "offer_uuid": offer_uuid,
        "team_uuid": team_uuid,
        "product_uuid": product_uuid,
        "product_name": product_name,
        "category_name": category_name,
        "location_uuid": location_uuid,
        "location_name": location_name,
        "location_country": location_country,
        "location_country_code": location_country_code,
        "location_latitude": location_latitude,
        "location_longitude": location_longitude,
        "quantity": str(quantity) if quantity is not None else None,
        "unit": unit,
        "price_per_unit": str(price_per_unit) if price_per_unit is not None else None,
        "currency": currency,
        "description": description,
        "valid_until": valid_until.isoformat() if hasattr(valid_until, "isoformat") else valid_until,
        "terminus_schema_id": terminus_schema_id,
        "terminus_payload": terminus_payload,
    }

    try:
        return asyncio.run(_start_offer_workflow_async(payload))
    except Exception:
        logger.exception("Failed to start offer workflow %s", offer_uuid)
        raise
