"""
Python CloudI external service template.

Copy this directory to services/[your_service_name]/ and:
1. Replace SERVICE_NAME and ServiceName with your service name
2. Replace [tenant_pattern]/[service_path] with the actual CloudI service path
   (must match what ServiceResolver.resolve/2 produces in adapter_cloudi)
3. Implement __process() with your vendor logic
4. Add dependencies to requirements.txt
5. Add a cloudi.conf entry in config/cloudi.conf

The subscribe path must match the ServiceResolver pattern:
  /{tenant_id}/{service_path}  (e.g. /+/fraud/check)
  "+" is the CloudI wildcard matching any tenant_id.
"""
import sys
import json
import logging

sys.path.append('/usr/local/lib/cloudi-2.0.7/api/python/')

from cloudi import API, terminate_exception

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] [CloudI:%(name)s] %(message)s'
)
logger = logging.getLogger('SERVICE_NAME')


class ServiceNameService:
    """
    CloudI external service template — Python.

    Replace SERVICE_NAME and ServiceName with actual service name.
    Subscribe path must match the route registered in cloudi.conf.
    """

    def __init__(self):
        self.__api = API(0)

    def run(self):
        try:
            # Subscribe path must match ServiceResolver output in adapter_cloudi
            # Pattern: /{tenant_id}/{service_path} — use "+/" to match any tenant
            self.__api.subscribe("+/service/path", self.__handle_request)
            logger.info("Service started, waiting for requests")
            self.__api.poll()
        except terminate_exception:
            logger.info("Service terminated cleanly")
        except Exception as e:
            logger.error(f"Service error: {e}", exc_info=True)

    def __handle_request(self, request_type, name, pattern,
                         request_info, request,
                         timeout, priority, trans_id, pid):
        try:
            # Parse incoming MW-Core message (JSON encoded by adapter_cloudi)
            payload = json.loads(request)

            # Safe context fields forwarded from MW-Core (trace_id, tenant_id only)
            info = json.loads(request_info) if request_info else {}
            trace_id = info.get('trace_id', 'unknown')
            tenant_id = info.get('tenant_id', 'unknown')

            logger.info(f"Processing request trace_id={trace_id} tenant_id={tenant_id}")

            # --- YOUR VENDOR LOGIC HERE ---
            result = self.__process(payload, info)
            # ------------------------------

            logger.info(f"Request complete trace_id={trace_id}")
            return json.dumps({"status": "ok", "data": result})

        except Exception as e:
            logger.error(f"Request failed: {e}", exc_info=True)
            return json.dumps({"status": "error", "reason": str(e)})

    def __process(self, payload, info):
        """
        Implement vendor-specific logic here.
        Full Python ecosystem available: pandas, numpy, scikit-learn,
        lxml, pydantic, requests, etc.

        Args:
            payload (dict): The deserialized MW-Core message payload
            info (dict): Context metadata (trace_id, tenant_id, message_type, etc.)

        Returns:
            dict: Result data to be returned to MW-Core
        """
        raise NotImplementedError("Implement vendor logic here")


if __name__ == '__main__':
    assert API.thread_count() == 1, "Single-threaded service required"
    ServiceNameService().run()
