"""Entry point module: train-system

Implements the entry-point by using Python or any other languages.
"""

import os
import json
import sys
import yaml


def entry_point(activity_index, training_data_dir, verbose=False):
    """Method to complete: you have to raise an exception if an error occured
    in the program.

    Train your system on an unknown activity. The command will read the
    contents of the activity index and train the system for the new activities.
    Data referenced to the activity-index is relative to the training data
    directory.

    Args:
        activity_index (str): Path to activity index json file
        training_data_dir (str): Path to training data directory
    """
    # Content of a training dir:
    # training/
    # +-- SimSA5_*/
    #   +-- SimSA5_*.txt
    #   +-- ex00*/
    #     +-- activities.yml
    #     +-- types.yml
    #     +-- geom.yml

    def json_load(path):
        with open(path, 'r') as fd:
            data = json.load(fd)
        return data

    def yml_load(path):
        with open(path, 'r') as fd:
            data = yaml.load(fd, Loader=yaml.FullLoader)
        return data

    def log(msg):
        if verbose:
            print("[Training] %s" % (msg))

    def read_ai(path):
        log("Reading activity-index.json")
        ai = json_load(path)
        acts = {'known': [], 'surprise': []}
        for activity in ai:
            if ai[activity].get('training', None) is None:
                acts['known'].append(activity)
            else:
                acts['surprise'].append(activity)
        log("Found %d known activities" % (len(acts['known'])))
        log("Found %d surprise activities" % (len(acts['surprise'])))

    def read_ex(path):
        for fn in ["activities", "types", "geom"]:
            content = yml_load("%s.yml" % (os.path.join(path, fn)))

    def read_training(path):
        acts = []
        for root, dirs, files in os.walk(path):
            for act_dir in dirs:
                acts.append(act_dir)
                dir_path = os.path.join(root, act_dir)
                # Try to get activity description
                desc_file = os.path.join(dir_path, "%s.txt" % (act_dir))
                with open(desc_file, 'r') as fd:
                    desc = fd.readlines()
                # Analysing examplars
                for _root, _dirs, _files in os.walk(dir_path):
                    for ex in _dirs:
                        read_ex(os.path.join(_root, ex))
                    log("[%s] Found %d examplars" % (act_dir, len(_dirs)))
                    break
            break
        log('Found %d surprise activities' % (len(acts)))

    try:
        read_ai(os.path.join(training_data_dir, activity_index))
        read_training(os.path.join(training_data_dir, "training"))
    except FileNotFoundError as e:
        print("ERROR: Missing file: %s" % (e.filename), file=sys.stderr)
        sys.exit(1)
