"""Activities for KYC service via GraphQL M2M endpoint."""

import logging

import httpx
from temporalio import activity

from optovia_workflows.types import (
    CreateKycProfileInput,
    CreateKycProfileResult,
)

from ..config import settings

logger = logging.getLogger(__name__)


CREATE_KYC_PROFILE_MUTATION = """
mutation CreateKycProfile($kycApplicationId: String!) {
    createKycProfile(kycApplicationId: $kycApplicationId) {
        success
        profileUuid
        message
    }
}
"""


@activity.defn(name="create_kyc_profile")
def create_kyc_profile(data: CreateKycProfileInput) -> CreateKycProfileResult:
    """
    Create KYCProfile record from KYCApplication via GraphQL M2M endpoint.

    This is called after KYC approval to add the company to profile list
    for periodic data refresh by Dagster.
    """
    if not settings.KYC_INTERNAL_URL:
        logger.warning("KYC_INTERNAL_URL is not set; skipping profile creation")
        return CreateKycProfileResult(
            success=False,
            message="KYC_INTERNAL_URL is not set",
        )

    url = f"http://{settings.KYC_INTERNAL_URL}/graphql/m2m/"

    logger.info(
        "Creating KYC profile for application %s",
        data.kyc_application_id,
    )

    with httpx.Client(timeout=settings.KYC_TIMEOUT) as client:
        response = client.post(
            url,
            json={
                "query": CREATE_KYC_PROFILE_MUTATION,
                "variables": {
                    "kycApplicationId": data.kyc_application_id,
                },
            },
            headers={"Content-Type": "application/json"},
        )
        response.raise_for_status()

        result = response.json()
        if "errors" in result:
            raise Exception(f"GraphQL errors: {result['errors']}")

        mutation_result = result.get("data", {}).get("createKycProfile", {})
        if not mutation_result.get("success"):
            raise Exception(f"Failed to create profile: {mutation_result.get('message')}")

    profile_uuid = mutation_result.get("profileUuid", "")

    logger.info("KYC profile created: uuid=%s", profile_uuid)

    return CreateKycProfileResult(
        success=True,
        profile_uuid=profile_uuid,
        message="Profile created",
    )


# Alias for backwards compatibility with old activity name
@activity.defn(name="create_kyc_monitoring")
def create_kyc_monitoring(data: CreateKycProfileInput) -> CreateKycProfileResult:
    """Backwards compatible alias for create_kyc_profile."""
    return create_kyc_profile(data)
