"""Activities to sync offers into graph via Prefect."""
import logging
import time
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.
    """
    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"]

            node_data = {
                "uuid": data.offer_uuid,
                "node_type": "offer",
                "location_uuid": data.location_uuid,
                "location_latitude": data.location_latitude,
                "location_longitude": data.location_longitude,
                "team_uuid": data.team_uuid,
                "product_uuid": data.product_uuid,
                "price_per_unit": data.price_per_unit,
                "currency": data.currency,
                "quantity": data.quantity,
                "unit": data.unit,
            }

            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", flow_run_id)

        poll_interval = 60
        max_polls = 20
        polls = 0

        while polls < max_polls:
            with httpx.Client(timeout=30) as client:
                flow_run_url = f"{settings.PREFECT_API_URL}/flow_runs/{flow_run_id}"
                response = client.get(flow_run_url)
                response.raise_for_status()
                flow_run = response.json()

            state_type = flow_run.get("state", {}).get("type")
            state_name = flow_run.get("state", {}).get("name", "")
            if state_type == "COMPLETED":
                return TriggerPrefectOfferSyncResult(success=True, flow_run_id=flow_run_id)
            if state_type in ("FAILED", "CANCELLED", "CRASHED"):
                return TriggerPrefectOfferSyncResult(
                    success=False,
                    flow_run_id=flow_run_id,
                    message=f"Flow run {state_type}: {state_name}",
                )

            polls += 1
            time.sleep(poll_interval)

        return TriggerPrefectOfferSyncResult(
            success=False,
            flow_run_id=flow_run_id,
            message=f"Timeout waiting for flow run {flow_run_id}",
        )
    except Exception as exc:
        logger.exception("Failed to trigger Prefect offer sync")
        return TriggerPrefectOfferSyncResult(success=False, message=str(exc))
