"""
oTelemetry.py - OpenTelemetry Configuration Wrapper

A modular and extensible library for initializing OpenTelemetry and applying
automatic instrumentations. It supports multiple exporter protocols, including
a custom OTLP/HTTP JSON endpoint, standard OTLP, and native GCP exporters,
configurable via environment variables.
"""

# --- Standard Library Imports ---
import os
import socket
import logging
from typing import Dict, Any
from dotenv import load_dotenv

# Load environment variables at the start
load_dotenv()

# --- OpenTelemetry Core Imports ---
from opentelemetry import trace, metrics
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource, SERVICE_NAME, SERVICE_INSTANCE_ID

# --- OTLP Exporter ---
#from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
#from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
#from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter

# --- Logging Integration ---
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.instrumentation.logging import LoggingInstrumentor

# A dedicated logger for this module
logger = logging.getLogger(__name__)

# Set level log
logger.setLevel(logging.INFO)
# Suppress verbose logs from OpenTelemetry libraries to avoid cluttering the output
logging.getLogger("opentelemetry").setLevel(logging.CRITICAL)
logging.getLogger("opentelemetry.sdk.metrics").setLevel(logging.CRITICAL)
logging.getLogger("opentelemetry.exporter.otlp").setLevel(logging.CRITICAL)
# Format time "YYYY-MM-DD HH:MM:SS"
time_format = os.getenv("OTEL_LOGS_TIME_FORMAT", "%Y-%m-%d %H:%M:%S")
# Configure log format: LEVEL:logger_name: -> message
formatter = logging.Formatter(fmt='%(levelname)s:%(name)s: [%(asctime)s] -> %(message)s', datefmt=time_format)
# Create handler, e.g. StreamHandler for console output
handler = logging.StreamHandler()
# Set formatter for handler
handler.setFormatter(formatter)
# Attach handler to logger
if not logger.hasHandlers():
    logger.addHandler(handler)
logger.propagate = False

# Global flag to ensure initialization runs only once
_telemetry_initialized = False
exporter_protocol = os.getenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json").lower()

def is_collector_reachable(host=None):
    """Check if the telemetry collector host is resolvable."""
    if host is None:
        host = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "https://telemetry.domain-anda.com/otel")
    try:
        socket.gethostbyname(host)
        return True
    except socket.error:
        return False
    
def _parse_key_value_pairs(env_var_str: str) -> Dict[str, Any]:
    """
    Parses a comma-separated key=value string into a dictionary.
    Example: "key1=value1,key2=value2" -> {"key1": "value1", "key2": "value2"}
    """
    if not env_var_str:
        return {}
    try:
        return dict(item.split("=", 1) for item in env_var_str.split(","))
    except ValueError:
        logger.error(f"Invalid format for environment variable: {env_var_str}")
        return {}
    
def _setup_resource() -> Resource:
    """
    Sets up the OpenTelemetry Resource by combining:
    - Automatic GCP resource detection (if applicable).
    - Attributes from OTEL_RESOURCE_ATTRIBUTES.
    - Service name from OTEL_SERVICE_NAME.
    """
    final_attributes = {}

    # Step 1: Start with automatic detection from GCP (Lowest Priority).
    if exporter_protocol in ["gcp_otlp"]:
        # logger.info(f"Trying GCP resource detection...")
        try:
            gcp_resource = get_aggregated_resources(
                [GoogleCloudResourceDetector(raise_on_error=False)]
            )
            final_attributes.update(gcp_resource.attributes)
        except Exception as e:
            logger.warning(f"Failed to run GCP Resource Detector: {e}")

    # Step 2: Override or add attributes from OTEL_RESOURCE_ATTRIBUTES.
    extra_attributes = _parse_key_value_pairs(
        os.getenv("OTEL_RESOURCE_ATTRIBUTES", "")
    )
    final_attributes.update(extra_attributes)

    # Step 3: Override or add attributes from OTEL_SERVICE_NAME (Highest Priority).
    service_name = os.getenv("OTEL_SERVICE_NAME")
    if service_name:
        #final_attributes["service.name"] = service_name.strip()
        final_attributes[SERVICE_NAME] = service_name.strip()

    # Step 4: Add unique instance ID.
    final_attributes[SERVICE_INSTANCE_ID] = f"worker-{os.getpid()}"

    resource = Resource.create(final_attributes)

    # Debug output to see the created attributes
    #print(f"DEBUG: Final Resource Attributes Created: {resource.attributes}")

    # Create the Resource object only once at the end of attribute merging.
    return resource

def _get_exporter(signal: str):
    """
    Selects and configures an exporter based on OTEL_EXPORTER_OTLP_PROTOCOL.
    The OpenTelemetry SDK automatically handles endpoint and header configuration
    from the standard OTEL_EXPORTER_OTLP_* environment variables.
    """
    endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "https://telemetry.domain-anda.com/otel")

    if exporter_protocol == "gcp_native_grpc":
        if signal == "traces":
            try:
                from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
                # logger.info("Using Google Cloud Trace Exporter (gRPC native).")
                return CloudTraceSpanExporter()
            except ImportError:
                logger.error("Library 'opentelemetry-exporter-gcp-trace' is not installed.")
                return None
        
        elif signal == "metrics":
            try:
                from opentelemetry.exporter.cloud_monitoring import CloudMonitoringMetricsExporter
                # logger.info("Using Google Cloud Monitoring Exporter (gRPC native).")
                return CloudMonitoringMetricsExporter()
            except ImportError:
                logger.error("Library 'opentelemetry-exporter-gcp-monitoring' is not installed.")
                return None
        
        elif signal == "logs":
            try:
                from opentelemetry.exporter.cloud_logging import CloudLoggingExporter
                # logger.info("Using Google Cloud Logging Exporter (gRPC native).")
                return CloudLoggingExporter()
            except ImportError:
                logger.error("Library 'opentelemetry-exporter-gcp-logging' is not installed.")
                return None
        else:
            logger.error(f"Signal {signal} is not recognized for exporter {exporter_protocol}")
            return None
    
    elif exporter_protocol == "gcp_otlp":
        import google.auth
        import google.auth.transport.grpc
        import google.auth.transport.requests
        import grpc
        # Use OTLP exporter for Google Cloud (trace, metrics, logs)
        endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "telemetry.googleapis.com:443")

        try:
            # 1. Get credentials from environment (ADC)
            # Define the scopes needed for Cloud Trace, Monitoring, and Logging
            scopes = ["https://www.googleapis.com/auth/cloud-platform"]
            credentials, project_id = google.auth.default(scopes=scopes)
            if not project_id:
                logger.error("Failed to obtain Project ID from Google Cloud credentials.")
                return None
        except google.auth.exceptions.DefaultCredentialsError:
            logger.error(
                "Failed to obtain Google Cloud credentials. "
                "Make sure you are logged in via 'gcloud auth application-default login' "
                "or Service Account is properly configured."
            )
            return None

        # Create secure gRPC credentials with Google authentication
        request = google.auth.transport.requests.Request()
        auth_plugin = google.auth.transport.grpc.AuthMetadataPlugin(credentials, request)
        auth_call_credentials = grpc.metadata_call_credentials(auth_plugin)
        grpc_channel_credentials = grpc.composite_channel_credentials(
            grpc.ssl_channel_credentials(),
            auth_call_credentials
        )

        # logger.info(f"Using OTLP Exporter for Google Cloud: {signal}")

        if signal == "traces":
            from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
            return OTLPSpanExporter(endpoint=endpoint, credentials=grpc_channel_credentials)
        elif signal == "metrics":
            from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
            return OTLPMetricExporter(endpoint=endpoint, credentials=grpc_channel_credentials)
        #elif signal == "logs":
        #   # Log exporter for GCP via OTLP is not commonly used; typically use CloudLoggingExporter
        #    from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
        #    return OTLPLogExporter(endpoint=endpoint, credentials=grpc_channel_credentials)
        else:
            logger.error(f"Signal {signal} is not recognized for exporter {exporter_protocol}")
            return None

    elif exporter_protocol == 'http/json':
        # Default to OTLP HTTP/JSON or gRPC based on endpoint format
        headers = _parse_key_value_pairs(os.getenv("OTEL_EXPORTER_OTLP_HEADERS", ""))
        headers["Content-Type"] = "application/json"
        headers["X-Telemetry-Service-Name"] = os.getenv("OTEL_SERVICE_NAME", "OpenTelemetry-Python-service")
        base_endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
        # logger.info(f"Using HTTP/JSON Exporter for signal '{signal}'.")
        if signal == "traces":
            from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
            # Gabungkan endpoint dasar dengan path spesifik untuk traces
            final_endpoint = f"{base_endpoint}/v1/traces"
            # final_endpoint = os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
            return OTLPSpanExporter(endpoint=final_endpoint, headers=headers)
        elif signal == "metrics":
            from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
            # Gabungkan endpoint dasar dengan path spesifik untuk metrics
            final_endpoint = f"{base_endpoint}/v1/metrics"
            # final_endpoint = os.getenv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT")
            return OTLPMetricExporter(endpoint=final_endpoint, headers=headers)
        elif signal == "logs":
            from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
            # Gabungkan endpoint dasar dengan path spesifik untuk logs
            final_endpoint = f"{base_endpoint}/v1/logs"
            # final_endpoint = os.getenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT")
            return OTLPLogExporter(endpoint=final_endpoint, headers=headers)
    
    if "http://" in endpoint or "https://" in endpoint:
        # Use HTTP Exporter if endpoint contains http/https scheme
        # logger.info(f"Using OTLP/HTTP Exporter for signal '{signal}'.")
        if signal == "traces":
            from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
            # return OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", headers=headers)
            return OTLPSpanExporter()
        elif signal == "metrics":
            from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
            # return OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", headers=headers)
            return OTLPMetricExporter()
        elif signal == "logs":
            from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
            # return OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", headers=headers)
            return OTLPLogExporter()
    else:
        # Use gRPC Exporter if no scheme (format: host:port)
        # logger.info(f"Using OTLP/gRPC Exporter for signal '{signal}'.")
        if signal == "traces":
            from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
            # return OTLPSpanExporter(endpoint=endpoint, headers=headers)
        elif signal == "metrics":
            from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
            # return OTLPMetricExporter(endpoint=endpoint, headers=headers)
        elif signal == "logs":
            from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
            # return OTLPLogExporter(endpoint=endpoint, headers=headers)
    
    return None

def initialize_telemetry():
    """
    Initializes the core OpenTelemetry SDK pillars (Tracing, Metrics, Logging)
    based on environment variables. This function is idempotent and should be
    called once at the application's startup.
    """
    global _telemetry_initialized
    if _telemetry_initialized:
        return

    if os.getenv("OTEL_SERVICE_DISABLED", "false").lower() == "true":
        # logger.info("OpenTelemetry is disabled via OTEL_SERVICE_DISABLED.")
        _telemetry_initialized = True
        return

    # --- 1. Resource Setup ---
    # The resource identifies the service that is emitting telemetry data.
    #service_name = os.getenv("OTEL_SERVICE_NAME", "unnamed-application-service")
    #resource = Resource.create(attributes={DEPLOY_SERVICE_NAME: service_name})
    resource = _setup_resource()

    # --- 2. Tracing Setup ---
    # The SDK automatically reads OTEL_EXPORTER_OTLP_TRACES_* variables.
    if os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENABLED", "false").lower() == "true":
        trace_exporter = _get_exporter("traces")
        if trace_exporter:
            tracer_provider = TracerProvider(resource=resource)
            trace.set_tracer_provider(tracer_provider)
            tracer_provider.add_span_processor(BatchSpanProcessor(trace_exporter))
            # tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
            # logger.info("OTLP Tracing initialized.")

    # --- 3. Metrics Setup ---
    # The SDK automatically reads OTEL_EXPORTER_OTLP_METRICS_* variables.
    if os.getenv("OTEL_EXPORTER_OTLP_METRICS_ENABLED", "false").lower() == "true":
        metrics_exporter = _get_exporter("metrics")
        if metrics_exporter:
            metric_reader = PeriodicExportingMetricReader(metrics_exporter)
            meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
            metrics.set_meter_provider(meter_provider)
            # logger.info("OTLP Metrics initialized.")

    # --- 4. Logging Setup ---
    # This instruments the standard `logging` module to add trace context.
    log_level = logging.getLevelName(os.getenv("OTEL_LOG_LEVEL", "INFO").upper())
    LoggingInstrumentor().instrument(set_logging_format=True, log_level=log_level)
    
    # Optionally, configure a handler to send logs directly via OTLP.
    if os.getenv("OTEL_EXPORTER_OTLP_LOGS_ENABLED", "false").lower() == "true":
        log_exporter = _get_exporter("logs")
        if log_exporter:
            logger_provider = LoggerProvider(resource=resource)
            # logger_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter()))
            logger_provider.add_log_record_processor(BatchLogRecordProcessor(log_exporter))
            handler = LoggingHandler(level=log_level, logger_provider=logger_provider)
            handler.setFormatter(formatter)
            # Add handler only if not already present
            if not any(isinstance(h, LoggingHandler) for h in logger.handlers):
                logger.addHandler(handler)
            # logger.info("OTLP Log Exporter initialized.")

    _telemetry_initialized = True


def apply_instrumentations(app=None, db_engine=None):
    """
    Applies automatic instrumentations for known libraries and frameworks.
    This function should be called after `initialize_telemetry`.
    """
    if os.getenv("OTEL_SERVICE_DISABLED", "false").lower() == "true":
        return
    
    if not is_collector_reachable():
        #logger.warning("Telemetry collector is not reachable. Skipping instrumentation.")
        return

    # --- System Metrics Instrumentation ---
    try:
        from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor
        
        # Create default config with all metrics enabled
        config = {
            "system.cpu.time.enabled": True,
            "system.memory.usage.enabled": True,
            "system.disk.io.enabled": True,
            "system.network.io.enabled": True,
            # Additional configs can be added here
        }

        # Check if running in development environment or has read access to /proc/diskstats
        if not os.access('/proc/diskstats', os.R_OK):
            # logger.warning("No read access to /proc/diskstats. Disabling disk-related system metrics.")
            config["system.disk.io.enabled"] = False
            config["system.disk.operations.enabled"] = False
            config["system.disk.time.enabled"] = False
        if not os.access('/proc/vmstat', os.R_OK):
            # logger.warning("No read access to /proc/vmstat. Disabling swap-related system metrics.")
            config["system.swap.usage.enabled"] = False
        
        # Inisialisasi instrumentor dengan konfigurasi dinamis
        SystemMetricsInstrumentor(config=config).instrument()
        # logger.info("System metrics instrumentation applied.")
    except ImportError:
        logger.warning("To instrument System Metrics, please install: opentelemetry-instrumentation-system-metrics")
    
    # --------------------------------------------------

    # --- Web Framework Instrumentation ---
    if app:
        app_type_name = type(app).__name__.lower()
        if 'flask' in app_type_name:
            try:
                from opentelemetry.instrumentation.flask import FlaskInstrumentor
                FlaskInstrumentor().instrument_app(app)
                # logger.info("Flask instrumentation applied.")
            except ImportError:
                logger.warning("To instrument Flask, please install: opentelemetry-instrumentation-flask")
        elif "fastapi" in app_type_name:
            try:
                from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
                FastAPIInstrumentor.instrument_app(app)
                # logger.info("FastAPI instrumentation applied.")
            except ImportError:
                logger.warning("To instrument FastAPI, please install: opentelemetry-instrumentation-fastapi")
        else:
            logger.warning(f"Application type '{app_type_name}' not recognized for automatic instrumentation.")
    
    # --- Django Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.django import DjangoInstrumentor
    #    DjangoInstrumentor().instrument()
    #    # logger.info("Django instrumentation applied (ensure this is called early in settings.py or apps.py).")
    #except Exception:
    #    # Not all apps use Django, so we silently pass if import fails
    #    pass

    # --- Database Instrumentation ---
    if db_engine:
        try:
            from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
            SQLAlchemyInstrumentor().instrument(engine=db_engine)
            # logger.info("SQLAlchemy instrumentation applied.")
        except ImportError:
            logger.warning("To instrument SQLAlchemy, please install: opentelemetry-instrumentation-sqlalchemy")

        # --- SQLAlchemy Async Instrumentation --- (uncomment if needed)
        #try:
        #    from opentelemetry.instrumentation.sqlalchemy_async import SQLAlchemyAsyncInstrumentor
        #    SQLAlchemyAsyncInstrumentor().instrument()
        #    logger.info("SQLAlchemy Async instrumentation applied.")
        #except ImportError:
        #    logger.warning("To instrument SQLAlchemy Async, please install: opentelemetry-instrumentation-sqlalchemy-async")

    # --- HTTP Request Client Instrumentation ---
    try:
        from opentelemetry.instrumentation.requests import RequestsInstrumentor
        RequestsInstrumentor().instrument()
        # logger.info("Requests instrumentation applied.")
    except ImportError:
        logger.warning("To instrument Requests, please install: opentelemetry-instrumentation-requests")
    
    # --- Additional Instrumentations can be added here ---
    # E.g., Celery, Redis, etc.
    # --------------------------------------------------

    # --- AioHttp Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.aiohttp import AioHttpInstrumentor
    #    AioHttpInstrumentor().instrument()
    #    logger.info("AioHttp instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument AioHttp, please install: opentelemetry-instrumentation-aiohttp")

    # --- HTTPX Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
    #    HTTPXClientInstrumentor().instrument()
    #    logger.info("HTTPX instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument HTTPX, please install: opentelemetry-instrumentation-httpx")

    # --- Redis Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.redis import RedisInstrumentor
    #    RedisInstrumentor().instrument()
    #    logger.info("Redis instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument Redis, please install: opentelemetry-instrumentation-redis")

    # --- RabbitMQ Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.rabbitmq import RabbitMQInstrumentor
    #    RabbitMQInstrumentor().instrument()
    #    logger.info("RabbitMQ instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument RabbitMQ, please install: opentelemetry-instrumentation-rabbitmq")

    # --- Celery Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.celery import CeleryInstrumentor
    #    CeleryInstrumentor().instrument()
    #    logger.info("Celery instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument Celery, please install: opentelemetry-instrumentation-celery")

    # --- Kafka Instrumentation --- (uncomment if needed)
    #try:
    #    from opentelemetry.instrumentation.kafka import KafkaInstrumentor
    #    KafkaInstrumentor().instrument()
    #    logger.info("Kafka instrumentation applied.")
    #except ImportError:
    #    logger.warning("To instrument Kafka, please install: opentelemetry-instrumentation-kafka")
