import json
import logging
import logging.config
import os
import sys

from .cache import cache
from .instance_id import SERVICE_INSTANCE_ID


@cache()
def get_relative_sys_filename(pathname):
  sys_paths = sorted(sys.path, key=len, reverse=True)
  if not sys_paths[-1]:
    sys_paths[-1] = os.getcwd()
  for sys_path in sys_paths:
    if sys_path and pathname.startswith(sys_path):
      return os.path.relpath(pathname, sys_path)
  return pathname


class OPFormatter(logging.Formatter):

  def format(self, record):
    relative_filename = get_relative_sys_filename(record.pathname)
    json_contents = {
      'l': record.levelname,
      'n': record.name,
      's': relative_filename,
      '#': record.lineno,
      'i': SERVICE_INSTANCE_ID,
      'm': super().format(record)
    }
    return "[OP]" + json.dumps(json_contents, separators=(',', ':'))


OP_LOG_CONFIG = {
  'version': 1,
  'disable_existing_loggers': False,
  'formatters': {
    'op_formatter': {
      '()': OPFormatter
    }
  },
  'handlers': {
    'default': {
      'formatter': 'op_formatter',
      'class': 'logging.StreamHandler'
    },
  },
  'root': {
    'handlers': [ 'default' ],
    'level': 'NOTSET'
  }
}


def configure_logging():
  logging.config.dictConfig(OP_LOG_CONFIG)
  logging.getLogger('fasteners.process_lock').setLevel(logging.WARNING)
  logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
  logging.getLogger('multipart.multipart').setLevel(logging.WARNING)
  logging.getLogger('hypercorn.access').setLevel(logging.WARNING)
  logging.getLogger('hypercorn.error').setLevel(logging.WARNING)
