"""CTCLR-09: one approved local policy; disabling cleanup never disables admission."""
import json
import os
from pathlib import Path

NAME = '.ct-storage-policy.json'
FIELDS = {'max_bytes', 'target_bytes', 'min_free_bytes', 'auto_cleanup'}


def validate(value):
    if type(value) is not dict or set(value) != {'version', 'artifact', 'training'} or type(value['version']) is not int or value['version'] != 1:
        raise ValueError('STORAGE_POLICY_SCHEMA')
    for kind in ('artifact', 'training'):
        row = value[kind]
        if type(row) is not dict or set(row) != FIELDS or type(row['auto_cleanup']) is not bool:
            raise ValueError('STORAGE_POLICY_FIELDS')
        for key in FIELDS - {'auto_cleanup'}:
            if type(row[key]) is not int or not 0 <= row[key] <= 10_000_000_000_000:
                raise ValueError('STORAGE_POLICY_BYTES')
        if not 128*1024**2 <= row['target_bytes'] <= row['max_bytes']:
            raise ValueError('STORAGE_POLICY_TARGET')
    return value


def load(environ=None):
    env = os.environ if environ is None else environ
    root = env.get('CONTEXTRA_ARTIFACT_ROOT')
    if not root:
        return None
    path = Path(root) / NAME
    if not path.exists() and not path.is_symlink():
        return None
    if any(p.is_symlink() for p in (path, *path.parents)) or not path.is_file() or path.stat().st_size > 16384:
        raise ValueError('STORAGE_POLICY_PATH')
    return validate(json.loads(path.read_text()))
