import logging
import os
from typing import Dict, Any

import requests
from temporalio import activity

from .types import TeamCreatedInput

logger = logging.getLogger(__name__)


def _odoo_client():
    """
    Returns callable that posts to Odoo; keeps auth and URL configuration in one place.
    """
    url = os.environ.get("ODOO_KYC_URL", "http://odoo:8069/fastapi/kyc/order")
    auth_user = os.environ.get("ODOO_KYC_AUTH_USER", "kyc_api")
    auth_pass = os.environ.get("ODOO_KYC_AUTH_PASS", "kyc_api_pass")
    timeout_seconds = float(os.environ.get("ODOO_KYC_TIMEOUT", "30"))

    def call(payload: Dict[str, Any]) -> Dict[str, Any]:
        response = requests.post(
            url,
            json=payload,
            headers={"Content-Type": "application/json"},
            auth=(auth_user, auth_pass) if auth_user else None,
            timeout=timeout_seconds,
        )
        response.raise_for_status()
        return response.json()

    return call


@activity.defn(name="create_kyc_in_odoo")
def create_kyc_in_odoo(data: TeamCreatedInput) -> Dict[str, Any]:
    """
    Activity: create KYC request in Odoo via FastAPI.
    Mirrors the current Prefect flow but runs under Temporal.
    """
    client = _odoo_client()
    payload = {
        "team_id": data.team_id,
        "team_name": data.team_name,
        "owner_id": data.owner_id,
        "logto_org_id": data.logto_org_id,
    }

    logger.info("Sending KYC creation to Odoo for team %s", data.team_id)
    result = client(payload)

    if not result.get("success"):
        # Surface a meaningful error to allow retries/backoff at the workflow level.
        raise RuntimeError(f"Odoo KYC API error: {result}")

    return result
