#!/usr/bin/env python3

print('''
filter_json.py - a script from the AQUAMIS pipeline:
https://gitlab.com/bfr_bioinformatics/AQUAMIS.git
''')

# %% Packages

# Python Standard Packages
import sys
import os
import json
from pprint import pprint

# Other Packages
import cerberus
from helper_functions import *

# %% DEBUG: Override Snakemake

try:
    snakemake.input[0]
except NameError:
    from filter_json_debug import *
    debug_mode = True
else:
    debug_mode = False

# %% Import Data

with open(snakemake.input['json_in'], 'r') as file:
    json_sample = json.load(fp=file)  # without arg object_pairs_hook=unquote_hook to mimic ExtendsClasses schema

# %% Logging

with open(snakemake.log['log'], "w") as logfile:
    if not debug_mode:
        sys.stderr = sys.stdout = logfile

    # %% Import Schema

    with open(snakemake.params['config']['params']['json_schema']['validation'], 'r') as file:
        json_schema_validation = json.load(fp=file)

    with open(snakemake.params['config']['params']['json_schema']['filter'], 'r') as file:
        json_schema_filter = json.load(fp=file)

    # %% Cerberus: Create Validator

    # Convert custom JSON schema to Cerberus schema
    cerberus_schema_validation = translateSchema_json2cerberus(schemaObj=json_schema_validation)['Root']['schema']
    cerberus_schema_filter = translateSchema_json2cerberus(schemaObj=json_schema_filter)['Root']['schema']
    cerberus_schema_validation_withDefault = translateSchema_json2cerberus(schemaObj=json_schema_validation, defaultValues=defaultValues_dict)['Root']['schema']

    # Create Validator objects
    validator_schema_validation = cerberus.Validator(cerberus_schema_validation, ignore_none_values=True, purge_unknown=True)
    validator_schema_filter = cerberus.Validator(cerberus_schema_filter, ignore_none_values=True, purge_unknown=True)
    validator_schema_validation_withDefaults = cerberus.Validator(cerberus_schema_validation_withDefault, ignore_none_values=True, purge_unknown=True)

    # %% Cerberus: Normalize with Validators

    json_sample_validated = validator_schema_validation.validate(json_sample)  # BEWARE of URL quoting
    json_sample_filtered = validator_schema_filter.normalized(json_sample)  # BEWARE of URL quoting # TODO: add schema rule for ['mlst']['alleles'] list for GMI-17-003-DNA
    json_sample_empty = validator_schema_validation_withDefaults.normalized({'sample': {}})

    if json_sample_validated:
        print(f'JSON Schema Validation of {list(json_sample.keys())[0]}: Passed.')
    else:
        print(f'JSON Schema Validation of {list(json_sample.keys())[0]}: FAILED.')
        with open(snakemake.output['json_out'].replace('.json', '_validationErrors.json'), 'w') as file:
            json.dump(validator_schema_validation.errors,
                      fp=file,
                      indent=4,
                      sort_keys=False,
                      ensure_ascii=False,
                      allow_nan=False)

    if json_sample_filtered == json_sample:
        print(f'JSON Schema Normalization of {list(json_sample.keys())[0]}: No changes.')
    else:
        print(f'Schema Normalization of {list(json_sample.keys())[0]}: Filtered.')

    # %% Write Output

    with open(snakemake.output['json_out'], 'w') as file:
        json.dump(json_sample_filtered,
                  fp=file,
                  indent=4,
                  sort_keys=False,
                  ensure_ascii=False,
                  allow_nan=False)
