# Copyright (c) TuxCare, Inc. All rights reserved.
# Licensed under TUXCARE LICENSE AGREEMENT
# https://tuxcare.com/legal/

import json
import os
import re
import time

from . import auth, config, constants, delivery_kit, fs_utils, http_utils, log_utils, platform_utils, utils

if False:  # pragma: no cover
    from typing import Any, Dict, List, Optional  # noqa: F401

LOG_FILE = '/proc/edf/log'
STATS_FILE = '/proc/edf/stats'
ENFORCING_FILE = '/proc/sys/edf/enforcing'
BOOT_ID_FILE = '/proc/sys/kernel/random/boot_id'
CURSOR_FILE = os.path.join(constants.PATCH_CACHE, 'edf.cursor')

LOG_ENTRY_RE = re.compile(
    r'^\[(?P<us>\d+)\] (?P<type>[^:]+): (?P<event>.+)\((?P<func>\w+)\): '
    r'(?P<parent_name>.+)\(pid:(?P<parent_pid>\d+) uid:(?P<parent_uid>\d+)\) --> '
    r'(?P<name>.+)\(pid:(?P<pid>\d+), uid:(?P<uid>\d+)\)$'
)
INT_FIELDS = ('us', 'parent_pid', 'parent_uid', 'pid', 'uid')
MAX_SIZE_BYTES = 1024**2


class EdfEventsPackage(delivery_kit.DataPackage):
    data_type = 'edf-events'
    upload_uri = '/upload/edf-events/'

    @property
    def max_size(self):
        # type: () -> int
        return MAX_SIZE_BYTES

    def _upload(self, upload_url):
        # type: (str) -> None
        # Runs inside every checkin: one attempt with the checkin's own
        # timeout, logged only, so a failing endpoint can't slow down or
        # clutter --info / --check. The events stay queued for the next one.
        http_utils.upload_file_once(
            self.archive_path,
            upload_url=upload_url,
            auth_string=auth.get_http_auth_string(),
            timeout=config.HTTP_TIMEOUT,
            print_errors=False,
        )


def parse_log(text):
    # type: (str) -> List[Dict[str, Any]]
    entries = []
    for line in text.splitlines():
        match = LOG_ENTRY_RE.match(line)
        if not match:
            continue

        entry = match.groupdict()  # type: Dict[str, Any]
        for field in INT_FIELDS:
            entry[field] = int(entry[field])
        entries.append(entry)
    return entries


def parse_stats(text):
    # type: (str) -> Dict[str, int]
    stats = {}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) == 2 and parts[1].isdigit():
            stats[parts[0]] = int(parts[1])
    return stats


def read_cursor():
    # type: () -> Dict[str, Any]
    try:
        with open(CURSOR_FILE) as f:
            cursor = json.load(f)
        return {'boot_id': str(cursor['boot_id']), 'us': int(cursor['us'])}
    except (IOError, OSError, ValueError, KeyError, TypeError):
        return {'boot_id': '', 'us': 0}


@utils.catch_errors(logger=log_utils.logwarn)
def save_cursor(edf_info):
    # type: (Optional[Dict[str, Any]]) -> None
    if not edf_info:
        return

    cursor = {'boot_id': edf_info['boot_id'], 'us': edf_info['last_event_us']}
    fs_utils.atomic_write(CURSOR_FILE, json.dumps(cursor))


def format_event(entry, boot_ts):
    # type: (Dict[str, Any], float) -> Dict[str, Any]
    event = dict(entry)
    event['ts'] = int(boot_ts + event.pop('us') / 1e6)
    return event


def boot_timestamp(now):
    # type: (float) -> float
    if constants.PY2:  # pragma: no py3 cover
        return now - int(platform_utils.get_uptime())
    return now - time.monotonic()  # pragma: no py2 cover


@utils.catch_errors(logger=log_utils.logwarn)
def collect(now):
    # type: (float) -> Optional[Dict[str, Any]]
    if not os.path.exists(LOG_FILE):
        return None

    boot_id = utils.read_file(BOOT_ID_FILE).strip()
    cursor = read_cursor()
    since_us = cursor['us'] if boot_id == cursor['boot_id'] else 0
    log = utils.nstr(utils.read_file_bin(LOG_FILE).decode('utf-8', 'replace'))
    new_entries = [entry for entry in parse_log(log) if entry['us'] > since_us]

    info = {
        'boot_id': boot_id,
        'last_event_us': new_entries[-1]['us'] if new_entries else since_us,
        'stats': parse_stats(utils.read_file(STATS_FILE, default='')),
    }  # type: Dict[str, Any]
    if new_entries:
        boot_ts = boot_timestamp(now)
        info['events'] = [format_event(entry, boot_ts) for entry in new_entries]
    return info


def status():
    # type: () -> str
    if not os.path.exists(LOG_FILE):
        return 'unavailable'
    try:
        enforcing = utils.read_file(ENFORCING_FILE).strip()
    except Exception as e:
        log_utils.logwarn('Failed to read EDF status: {0}'.format(e), print_msg=False)
        return 'error'
    return 'enforcing' if enforcing == '1' else 'monitoring'


def pending_events():
    # type: () -> Optional[Dict[str, Any]]
    edf_info = collect(time.time())  # type: Optional[Dict[str, Any]]
    if edf_info and edf_info.get('events'):
        return edf_info
    return None


def send_events(edf_info, sinfo):
    # type: (Dict[str, Any], Dict[str, Any]) -> None
    package = EdfEventsPackage()
    try:
        with package:
            package.add_json('edf.json', edf_info)
            package.add_json('server_info.json', sinfo)
        upload_name = package.send()
        save_cursor(edf_info)
        log_utils.loginfo('EDF events uploaded: {0}'.format(upload_name), print_msg=False)
    except Exception as e:
        log_utils.logwarn('Failed to send EDF events: {0}'.format(e), print_msg=False)
    finally:
        package.remove_archive()
