#!/usr/bin/env python3

"""
Deep schema validator for lava job/connector/trigger specifications.

!!! note
    We don't use any lava libraries in here deliberately because we want to use
    the same code in the lava job framework which may not have jinlava installed.
"""

from __future__ import annotations

import argparse
import os
import sys
from collections.abc import Iterable
from dataclasses import dataclass
from decimal import Decimal
from fnmatch import fnmatchcase
from functools import cache, partial
from pathlib import Path
from typing import Any
from urllib.error import HTTPError
from urllib.request import urlopen

import boto3
import jsonschema
import yaml
from boto3.dynamodb.types import TypeDeserializer
from colorama import Fore, Style, init

PROG = Path(sys.argv[0]).stem

SCHEMA_BASE = 'https://jin-gizmo.github.io/lava/schemas/latest'

SCHEMA_TYPE_DEFAULT = 'job'
ERROR_FORMAT = """[{n}] Validator: {err.validator}
    Path: {err.json_path}
    Message: {err.message}
    """

init()


# ------------------------------------------------------------------------------
def cprint(colour, *args, **kwargs):
    """Print in colour."""

    print(colour, sep='', end='', **kwargs)
    print(*args, end='', **kwargs)
    print(Style.RESET_ALL, **kwargs)


info = partial(cprint, Fore.GREEN)
warning = partial(cprint, Fore.YELLOW)
error = partial(cprint, Fore.RED)


# ------------------------------------------------------------------------------
@dataclass(frozen=True)
class LavaTableInfo:
    """Lava DynamoDB table names and corresponding hash key."""

    table: str  # This will have the realm name formatted in
    key: str


LAVA_TABLE_INFO = {
    'job': LavaTableInfo('lava.{realm}.jobs', 'job_id'),  # noqa
    's3trigger': LavaTableInfo('lava.{realm}.s3triggers', 'trigger_id'),
    'connection': LavaTableInfo('lava.{realm}.connections', 'conn_id'),
    'realm': LavaTableInfo('lava.realms', 'realm'),
    # None means there is schema for this entity but no associated table.
    'event-rule': None,
}


# ------------------------------------------------------------------------------
class CustomTypeDeserializer:
    """DynamoDB type deserializer that converts decimals to int / float."""

    def __init__(self):
        """Wrap the standard deserializer."""
        self._deserializer = TypeDeserializer()

    def deserialize(self, value):
        """Wrap the standard deserializer."""
        result = self._deserializer.deserialize(value)
        return self._convert_decimals(result)

    def _convert_decimals(self, obj):
        """Convert decimal to int / float."""
        if isinstance(obj, list):
            return [self._convert_decimals(i) for i in obj]
        if isinstance(obj, dict):
            return {k: self._convert_decimals(v) for k, v in obj.items()}
        if isinstance(obj, Decimal):
            return int(obj) if obj % 1 == 0 else float(obj)
        return obj


# ------------------------------------------------------------------------------
def process_cli_args() -> argparse.Namespace:
    """
    Process the command line arguments.

    :return:    The args namespace.
    """

    argp = argparse.ArgumentParser(
        prog=PROG,
        description='Deep schema validation for lava DynamoDB specification objects.',
        epilog='Exits with status 1 if any item fails validation and 0 otherwise.',
    )

    argp.add_argument(
        '-d',
        '--dynamodb',
        action='store_true',
        help=(
            'Read lava specifications from DynamoDB instead of the local file system.'
            ' The lava realm must be specified, either via the -r / --realm option or'
            ' the LAVA_REALM environment variable. Note that not all schema types'
            ' have an associated DynamoDB table.'
        ),
    )

    argp.add_argument(
        '-r',
        '--realm',
        action='store',
        default=os.environ.get('LAVA_REALM'),
        help=(
            'Lava realm name. If not specified, the environment variable LAVA_REALM'
            ' will be used. If --d / --dynamodb is specified, a value must be specified'
            ' by one of these mechanisms for realm specific tables.'
        ),
    )

    argp.add_argument(
        '-s',
        '--schema-base',
        action='store',
        default=os.environ.get('LAVA_SCHEMA_BASE', SCHEMA_BASE),
        help=(
            'Path to schema base directory. This can be a local directory or a URL.'
            f' If not specified, the value of the LAVA_SCHEMA_BASE environment'
            f' variable is used with a default of {SCHEMA_BASE}.'
        ),
    )

    argp.add_argument(
        '-t',
        '--type',
        action='store',
        dest='component_type',
        choices=LAVA_TABLE_INFO,
        default=SCHEMA_TYPE_DEFAULT,
        help=(
            'Use the schema appropriate to the specified lava object type.'
            f' The default is {SCHEMA_TYPE_DEFAULT}.'
        ),
    )

    argp.add_argument(
        '-v',
        '--verbose',
        action='store_true',
        help=(
            'Print results for all specifications. By default, only'
            ' validation failures are printed.'
        ),
    )

    argp.add_argument(
        'spec',
        metavar='SPEC',
        nargs='*',
        help=(
            'If the -d / --dynamodb option is specified, specifications are read'
            ' directly from DynamoDB and any SPEC arguments are treated as GLOB'
            ' style patterns that the ID of the specifications must match.'
            ' If the -d / --dynamodb option is not specified, JSON or YAML formatted'
            ' lava object specifications are read from the named files.'
            ' Note that any $schema entries in the source are ignored in favour'
            ' of the schemas indicated by -s / --schema-base.'
        ),
    )

    args = argp.parse_args()

    if args.dynamodb and '{realm}' in LAVA_TABLE_INFO[args.component_type].table and not args.realm:
        argp.error(
            f'Realm must be specified to access items of type "{args.component_type}" in DynamoDB'
        )

    return args


# ------------------------------------------------------------------------------
def lava_specs_local(*filenames: str) -> Iterable[tuple[str, dict]]:
    """
    Read lava specifications from files and return them.

    :param filenames:   Names of files containing lava DynamoDB table specs.
    :return:            An iterator over tuples (file name, contents).
    """

    return ((spec_file, yaml.safe_load(Path(spec_file).read_text())) for spec_file in filenames)


# ------------------------------------------------------------------------------
@cache
def load_table(
    table_name: str, key: str, aws_session: boto3.Session = None
) -> dict[str, dict[str, Any]]:
    """
    Read the entire contents of a table into memory and cache it.

    Be careful with this in terms of memory use and DynamoDB full table scans.

    :param table_name:      Name of the table.
    :param key:             The table hash key.
    :param aws_session:     A boto3 Session().

    :return:                A dict of table items keyed on the table key.
    """

    dynamo = (aws_session or boto3.Session()).client('dynamodb')
    deserializer = CustomTypeDeserializer()
    entries = {}

    paginator = dynamo.get_paginator('scan')
    response_iterator = paginator.paginate(TableName=table_name, Select='ALL_ATTRIBUTES')

    for response in response_iterator:
        for item in response['Items']:
            # Boto3 API for Dynamo sucks so hard it could pull chrome off a bullbar
            item = {k: deserializer.deserialize(v) for k, v in item.items()}
            entries[item[key]] = item

    return entries


# ------------------------------------------------------------------------------
def lava_specs_dynamo(spec_type: str, realm: str, *patterns: str) -> Iterable[tuple[str, dict]]:
    """
    Read lava specifications from DynamoDB.

    :param spec_type:   Determines which table to read.
    :param realm:       Lava realm.
    :param patterns:    Zero or more glob patterns. If present, the spec ID must
                        match one of them.
    :return:            An iterator over tuples (spec ID, contents).
    """

    table_info = LAVA_TABLE_INFO[spec_type]
    if not table_info:
        raise Exception(f'{spec_type} does not have an associated DynamoDB table')

    for spec_id, spec in load_table(
        table_info.table.format(realm=realm), table_info.key, aws_session=boto3.Session()
    ).items():
        if not patterns or any(fnmatchcase(spec_id, p) for p in patterns):
            yield spec_id, spec


# ------------------------------------------------------------------------------
def load_schema(schema_base: str, component_type: str) -> dict[str, Any]:
    """Load the schema for the specified component type."""

    schema_fqn = f'{schema_base}/{component_type}.schema.json'
    schema_text = None
    if schema_fqn.startswith(('https://', 'http://')):
        try:
            with urlopen(schema_fqn) as response:  # noqa: S310
                if response.status != 200:
                    raise Exception(f'{schema_fqn}: {response.reason}')
                schema_text = response.read().decode('utf-8')
        except HTTPError as e:
            raise Exception(f'{schema_fqn}: {e}') from e
    else:
        try:
            schema_text = Path(schema_fqn).read_text()
        except OSError as e:
            raise Exception(f'{schema_fqn}: {e}') from e

    try:
        # ok for YAML or JSON
        schema = yaml.safe_load(schema_text)
    except yaml.YAMLError as e:
        raise Exception(f'{schema_fqn}: {e}') from e

    return schema


# ------------------------------------------------------------------------------
def main() -> int:
    """Showtime."""

    args = process_cli_args()

    schema = load_schema(args.schema_base, args.component_type)
    validator_cls = jsonschema.validators.validator_for(schema)
    validator_cls.check_schema(schema)
    validator = validator_cls(schema)

    spec_getter = (
        partial(lava_specs_dynamo, args.component_type, args.realm)
        if args.dynamodb
        else lava_specs_local
    )

    status = 0
    for spec_id, spec in spec_getter(*args.spec):
        try:
            errors = list(validator.iter_errors(spec))
        except Exception as e:
            # This means something has gone wrong with the validation process.
            # This could be an error in the underlying schema that the schema
            # validation failed to find or a bug in jsonschema. Have seen both.
            # We deliberately don't count this as an error because we can't be
            # sure there is anything wrong with the instance being checked.
            warning(f'{spec_id}: Internal error - please report it: {e}')
            continue
        if not errors:
            if args.verbose:
                info(f'{spec_id}: OK')
            continue

        status = 1
        error(f'{spec_id}: Failed')
        for n, schema_error in enumerate(errors, start=1):
            print(ERROR_FORMAT.format(n=n, err=schema_error))

    return status


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    # Uncomment for debugging
    # exit(main())  # noqa: ERA001
    try:
        exit(main())
    except Exception as ex:
        print(f'{PROG}: {ex}', file=sys.stderr)
        exit(1)
    except KeyboardInterrupt:
        print('Interrupt', file=sys.stderr)
        exit(2)
