"""Last line of defence for FTP: the transport arm (DATA_DIR/scheduler/exports-arm.json).

No STOR happens unless a valid, unexpired arm file allows the very profile being used. The check is made directly in
``portal_transport.upload_portal_zip`` BEFORE the transport object (or any socket) is created, so it cannot be bypassed by
dispatch, automation, recovery, a restarted process or a caller-supplied ftp factory. State lives only in the file and is
re-read on every call (no cache), so the active policy is always the explicitly persisted operator choice.

Fail closed: missing, unreadable, corrupt, malformed, future-dated, expired, over-long or profile-less arms all forbid transport.
The default is OFF. Arming is an explicit operator action (CLI or the master-only, CSRF-protected export panel). It is either
time-limited (at most 24 h) or explicitly permanent; permanent arms retain the same profile gate and can be revoked with
``disarm``. ACK-only, recovery and every operation that does not call the uploader are unaffected.
Refusals are audited (code and profile NAME only) into the bounded ``exports.log``; credentials, hosts and paths are never logged.
Importing this module performs no I/O.
"""
from datetime import datetime, timezone
import json
import logging
from logging.handlers import RotatingFileHandler
import re
import time

NAME = 'exports-arm.json'
VERSION = 1
MAX_SECONDS = 24 * 3600
SKEW = 60                       # tolerated clock skew for "armed in the future" (seconds)
KEYS = {'version', 'arm_version', 'profiles', 'armed_at', 'expires_at', 'armed_by'}
STAMP = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$')
CODES = ('armed', 'arm_missing', 'arm_corrupt', 'arm_expired', 'arm_not_yet_valid', 'arm_profile_not_allowed', 'arm_unavailable')


def _scheduler():
    from InvestmentManager import scheduler_state
    return scheduler_state


def _profiles():
    from . import export_transport_config as config
    return config.PROFILES


def _epoch(text):
    return datetime.strptime(text, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).timestamp()


def _stamp(epoch):
    return datetime.fromtimestamp(epoch, timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')


def _validate(value):
    if not isinstance(value, dict) or set(value) != KEYS or type(value['version']) is not int or value['version'] != VERSION:
        raise ValueError('shape')
    if type(value['arm_version']) is not int or value['arm_version'] < 1:
        raise ValueError('arm_version')
    profiles = value['profiles']
    if (not isinstance(profiles, list) or not profiles or len(set(profiles)) != len(profiles)
            or any(not isinstance(item, str) or item not in _profiles() for item in profiles)):
        raise ValueError('profiles')
    if not isinstance(value['armed_at'], str) or not STAMP.fullmatch(value['armed_at']):
        raise ValueError('armed_at')
    if not isinstance(value['expires_at'], str) or (value['expires_at'] != 'never' and not STAMP.fullmatch(value['expires_at'])):
        raise ValueError('expires_at')
    if not isinstance(value['armed_by'], str) or not 1 <= len(value['armed_by']) <= 96:
        raise ValueError('armed_by')
    if value['expires_at'] != 'never':
        start, end = _epoch(value['armed_at']), _epoch(value['expires_at'])
        if not 0 < end - start <= MAX_SECONDS:
            raise ValueError('duration')
    return value


def read():
    """{'status': 'missing'|'ok'|'corrupt'|'unavailable', 'arm': dict|None}. Never raises. An existing file that does not
    hold a valid arm (including JSON ``null``) is 'corrupt', never 'missing'."""
    try:
        scheduler = _scheduler()
        exists = (scheduler.directory() / NAME).exists()
        value = scheduler.read(NAME, None) if exists else None
    except Exception as exc:
        text = str(exc)
        return {'status': 'corrupt' if text.startswith('invalid_') else 'unavailable', 'arm': None}
    if not exists:
        return {'status': 'missing', 'arm': None}
    try:
        return {'status': 'ok', 'arm': _validate(value)}
    except (ValueError, TypeError, KeyError):
        return {'status': 'corrupt', 'arm': None}


def check(profile, *, now=None):
    """Is a real transfer to ``profile`` allowed right now? {'allowed': bool, 'code': str}. Never raises, never caches."""
    state = read()
    if state['status'] != 'ok':
        return {'allowed': False, 'code': {'missing': 'arm_missing', 'corrupt': 'arm_corrupt'}.get(state['status'], 'arm_unavailable')}
    arm = state['arm']
    moment = time.time() if now is None else now
    if _epoch(arm['armed_at']) > moment + SKEW:
        return {'allowed': False, 'code': 'arm_not_yet_valid'}
    if arm['expires_at'] != 'never' and moment >= _epoch(arm['expires_at']):
        return {'allowed': False, 'code': 'arm_expired'}
    if not isinstance(profile, str) or profile not in arm['profiles']:
        return {'allowed': False, 'code': 'arm_profile_not_allowed'}
    return {'allowed': True, 'code': 'armed'}


def refuse(profile, code):
    """Audit one refusal (code + profile name only) into the bounded exports.log. Failure to audit never changes the refusal."""
    try:
        path = _scheduler().directory(create=True) / 'exports.log'
        logger = logging.Logger('investment.exports.arm')
        handler = RotatingFileHandler(path, maxBytes=1024 * 1024, backupCount=3, encoding='utf-8')
        handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
        logger.addHandler(handler)
        name = profile if isinstance(profile, str) and profile in _profiles() else 'invalid'
        logger.warning(json.dumps({'transport_refused': {'code': code, 'profile': name}}, sort_keys=True))
        handler.close()
    except Exception:
        pass


def arm(profiles, *, minutes=None, permanent=False, armed_by=None, now=None):
    """Explicit operator action. Allow profiles for 1..1440 minutes or permanently; replaces the previous arm."""
    from .export_control import ControlBusy
    from .input_consistency import input_lock, ConsistencyError
    import getpass
    if type(permanent) is not bool or permanent == (minutes is not None):
        raise ValueError('choose exactly one arm duration')
    if not permanent and (type(minutes) is not int or not 1 <= minutes * 60 <= MAX_SECONDS):
        raise ValueError('invalid arm duration')
    moment = int(time.time() if now is None else now)
    try:
        who = (armed_by or getpass.getuser())[:96] or 'local'
    except Exception:
        who = 'local'
    try:
        guard = input_lock()
        guard.__enter__()
    except ConsistencyError as exc:
        raise ControlBusy() from exc
    try:
        current = read()
        previous = current['arm']['arm_version'] if current['arm'] else 0
        value = {'version': VERSION, 'arm_version': previous + 1, 'profiles': list(profiles), 'armed_at': _stamp(moment),
                 'expires_at': 'never' if permanent else _stamp(moment + minutes * 60), 'armed_by': who}
        _validate(value)
        _scheduler().write(NAME, value)
        return read()
    finally:
        guard.__exit__(None, None, None)


def disarm():
    """Remove the arm file (transport forbidden at once). Idempotent."""
    import os
    path = _scheduler().directory(create=True) / NAME
    if path.is_symlink():
        raise ValueError('unsafe path')
    try:
        os.unlink(path)
        return {'status': 'disarmed'}
    except FileNotFoundError:
        return {'status': 'missing'}
