"""
Read what this install is running.

Used in two places:
  - ft_checkin, to build the payload a tenant sends to Final Target
  - the Fleet page, so the master install fills in its own row without
    having to make an HTTP call to itself
"""
import platform

import django
from django.conf import settings


def os_details():
    """Distribution name and version, falling back to the kernel."""
    name, version = '', ''
    try:
        with open('/etc/os-release', 'r', encoding='utf-8') as fh:
            data = {}
            for line in fh:
                if '=' in line:
                    key, _, value = line.partition('=')
                    data[key.strip()] = value.strip().strip('"')
        name = data.get('NAME', '')
        version = data.get('VERSION_ID', '')
    except OSError:
        pass
    if not name:
        name = platform.system()
        version = platform.release()
    return name, version


def db_engine():
    engine = settings.DATABASES.get('default', {}).get('ENGINE', '')
    return engine.rsplit('.', 1)[-1] if engine else ''


def local_report(tenant=None):
    """
    Everything this install knows about itself.
    Pass a tenant to include its plan and enabled modules.
    """
    name, version = os_details()
    report = {
        'ft_version': getattr(settings, 'CMS_VERSION', ''),
        'os_name': name,
        'os_version': version,
        'python_version': platform.python_version(),
        'django_version': django.get_version(),
        'db_engine': db_engine(),
        'hostname': platform.node(),
    }
    if tenant is not None:
        report['plan'] = getattr(tenant, 'plan', '')
        try:
            report['modules_enabled'] = sorted(tenant.enabled_module_keys)
        except Exception:
            report['modules_enabled'] = []
    return report


def apply_to_tenant(tenant):
    """
    Write this install's own details onto a Tenant row and save.
    Used for the master, which never checks in over HTTP.
    """
    from django.utils import timezone

    report = local_report(tenant)
    tenant.reported_version = report['ft_version'][:20]
    tenant.os_name = report['os_name'][:60]
    tenant.os_version = report['os_version'][:40]
    tenant.python_version = report['python_version'][:20]
    tenant.django_version = report['django_version'][:20]
    tenant.db_engine = report['db_engine'][:30]
    tenant.last_checkin_at = timezone.now()
    tenant.save(update_fields=[
        'reported_version', 'os_name', 'os_version', 'python_version',
        'django_version', 'db_engine', 'last_checkin_at',
    ])
    return tenant
