"""
Activities for Odoo ERP integration.
"""

import logging

import httpx
from temporalio import activity

from optovia_workflows.types import (
    AddKycToOdooResult,
    KycData,
    SetBuyerLogtoOrgInput,
    SetBuyerLogtoOrgResult,
)

from ..config import settings

logger = logging.getLogger(__name__)


@activity.defn(name="add_kyc_to_odoo")
def add_kyc_to_odoo(data: KycData) -> AddKycToOdooResult:
    """
    Create KYC application in Odoo ERP (partners module).

    This is a synchronous activity (runs in ThreadPoolExecutor).
    Uses httpx for HTTP requests with proper timeout handling.
    """
    url = f"http://{settings.ODOO_INTERNAL_URL}/fastapi/partners/kyc/applications"

    # Extract country-specific data (inn, ogrn for Russia)
    country_data = data.country_data or {}

    payload = {
        "workflow_id": data.kyc_request_id,
        "team_name": data.team_name,
        "owner_id": data.owner_id,
        "owner_email": data.owner_email or "",
        "country_code": data.country_code or "",
        "tax_id": country_data.get("inn", ""),
        "registration_number": country_data.get("ogrn", ""),
    }

    logger.info(
        "Creating KYC application in Odoo for workflow %s (team_name=%s)",
        data.kyc_request_id,
        data.team_name,
    )

    auth = None
    if settings.ODOO_KYC_AUTH_USER:
        auth = (settings.ODOO_KYC_AUTH_USER, settings.ODOO_KYC_AUTH_PASS)

    with httpx.Client(timeout=settings.ODOO_KYC_TIMEOUT) as client:
        response = client.post(
            url,
            json=payload,
            headers={"Content-Type": "application/json"},
            auth=auth,
        )
        response.raise_for_status()
        result = response.json()

    logger.info(
        "KYC application created in Odoo: id=%s, name=%s",
        result.get("id"),
        result.get("name"),
    )

    return AddKycToOdooResult(
        success=True,
        odoo_application_id=result.get("id"),
        application_name=result.get("name", ""),
        message="Application created successfully",
    )


@activity.defn(name="set_buyer_logto_org")
def set_buyer_logto_org(data: SetBuyerLogtoOrgInput) -> SetBuyerLogtoOrgResult:
    """
    Set Logto organization ID on buyer after org creation.

    Called by workflow after Logto org is created.
    """
    url = f"http://{settings.ODOO_INTERNAL_URL}/fastapi/partners/buyers/{data.team_uuid}/logto-org"

    payload = {
        "logto_org_id": data.logto_org_id,
    }

    logger.info(
        "Setting Logto org ID on buyer: team=%s, logto_org=%s",
        data.team_uuid,
        data.logto_org_id,
    )

    auth = None
    if settings.ODOO_KYC_AUTH_USER:
        auth = (settings.ODOO_KYC_AUTH_USER, settings.ODOO_KYC_AUTH_PASS)

    with httpx.Client(timeout=settings.ODOO_KYC_TIMEOUT) as client:
        response = client.post(
            url,
            json=payload,
            headers={"Content-Type": "application/json"},
            auth=auth,
        )
        response.raise_for_status()
        result = response.json()

    logger.info(
        "Buyer updated with Logto org: buyer_uuid=%s",
        result.get("buyer_uuid"),
    )

    return SetBuyerLogtoOrgResult(
        success=True,
        buyer_uuid=result.get("buyer_uuid", ""),
        message="Buyer updated successfully",
    )
