import grpc
import logging
from datetime import datetime

from .utils import get_creds
from .config import ENV_CONFIG
from .grpc_options import COMMON_CHANNEL_OPTIONS
from google.protobuf.struct_pb2 import Struct
from google.protobuf.timestamp_pb2 import Timestamp
from yandex.cloud.logging.v1 import log_ingestion_service_pb2, log_ingestion_service_pb2_grpc, log_entry_pb2, log_resource_pb2

logger = logging.getLogger(__name__)


def write(log_group_id, log_data, resource_type, resource_id, token, level=None, request_id=None, timeout=100.0, logging_host=None, logging_port=None):
    logging_host = logging_host or ENV_CONFIG.LOGGING_HOST
    logging_port = logging_port or ENV_CONFIG.LOGGING_PORT
    channel = grpc.secure_channel(
        f"{logging_host}:{logging_port}",
        get_creds(logging_host, logging_port, token),
        options=COMMON_CHANNEL_OPTIONS,
    )
    stub = log_ingestion_service_pb2_grpc.LogIngestionServiceStub(channel)

    destination = log_entry_pb2.Destination(log_group_id=log_group_id)
    log_resource = log_resource_pb2.LogEntryResource(type=resource_type, id=resource_id)
    level = level or log_entry_pb2.LogLevel.Level.INFO
    json_payload = Struct()
    json_payload.update({"request_id": request_id})
    current_time = Timestamp(seconds=int(datetime.utcnow().timestamp()))
    entry_logs = [log_entry_pb2.IncomingLogEntry(message=data, level=level, json_payload=json_payload, timestamp=current_time) for data in log_data]

    request = log_ingestion_service_pb2.WriteRequest(destination=destination, resource=log_resource, entries=entry_logs)
    response = stub.Write(request, timeout, metadata=[('x-request-id', request_id)])
    logger.debug(f"Sent logs to logging service: {response}")
    return response
