"""Activities to sync offers into graph via Prefect."""
import logging
import httpx
from temporalio import activity

from optovia_workflows.types import TriggerPrefectOfferSyncInput, TriggerPrefectOfferSyncResult
from ..config import settings

logger = logging.getLogger(__name__)


@activity.defn(name="trigger_prefect_offer_sync")
def trigger_prefect_offer_sync(data: TriggerPrefectOfferSyncInput) -> TriggerPrefectOfferSyncResult:
    """
    Trigger Prefect sync-offer flow to create offer node and edge to location.

    Creates flow run and returns immediately. Prefect will signal Temporal
    when the flow completes.
    """
    try:
        deployment_url = f"{settings.PREFECT_API_URL}/deployments/name/sync-offer/sync-offer-deployment"

        with httpx.Client(timeout=30) as client:
            response = client.get(deployment_url)
            response.raise_for_status()
            deployment_id = response.json()["id"]

            # Include workflow_id so Prefect can signal back
            node_data = {
                "uuid": data.offer_uuid,
                "node_type": "offer",
                "location_uuid": data.location_uuid,
                "location_latitude": data.location_latitude,
                "location_longitude": data.location_longitude,
                "supplier_uuid": data.supplier_uuid,
                "team_uuid": data.team_uuid,
                "product_uuid": data.product_uuid,
                "product_name": data.product_name,
                "price_per_unit": data.price_per_unit,
                "currency": data.currency,
                "quantity": data.quantity,
                "unit": data.unit,
                "workflow_id": data.workflow_id,
            }

            run_url = f"{settings.PREFECT_API_URL}/deployments/{deployment_id}/create_flow_run"
            response = client.post(run_url, json={"parameters": {"offer_data": node_data}})
            response.raise_for_status()
            flow_run_id = response.json()["id"]

            logger.info(
                "Created Prefect offer flow run %s for workflow %s",
                flow_run_id,
                data.workflow_id,
            )

        # Return immediately - Prefect will signal when done
        return TriggerPrefectOfferSyncResult(success=True, flow_run_id=flow_run_id)

    except httpx.HTTPStatusError as exc:
        if exc.response.status_code >= 500:
            logger.warning("Prefect returned %s, will retry", exc.response.status_code)
            raise
        logger.exception("Failed to trigger Prefect offer sync")
        return TriggerPrefectOfferSyncResult(success=False, message=str(exc))
    except Exception as exc:
        logger.exception("Failed to trigger Prefect offer sync")
        return TriggerPrefectOfferSyncResult(success=False, message=str(exc))
