"""Exports control file (pause/resume of NEW starts). DATA_DIR/scheduler/exports-control.json v1.

Missing file means dispatch OFF and automation OFF; a corrupt file is fail-closed for new STARTs.
Pause/resume take the input lock (non-blocking) and never the runner lock, so a pause can be
committed while a long export is running. Import performs no I/O.
"""
import getpass
import time
from datetime import datetime, timezone

from . import export_jobs

NAME = 'exports-control.json'
KEYS = {'version', 'control_version', 'dispatch_enabled', 'automation_enabled', 'changed_at', 'changed_by'}


class ControlBusy(Exception):
    code = 'control_busy'


class ControlConflict(Exception):
    code = 'control_version_conflict'


def _scheduler():
    from InvestmentManager import scheduler_state
    return scheduler_state


def _validate(value):
    if (not isinstance(value, dict) or set(value) != KEYS or type(value['version']) is not int or value['version'] != 1
            or type(value['control_version']) is not int or value['control_version'] < 1
            or type(value['dispatch_enabled']) is not bool or value['automation_enabled'] is not False
            or not isinstance(value['changed_at'], str) or not isinstance(value['changed_by'], str)
            or len(value['changed_by']) > 96):
        raise ValueError('invalid control')
    return value


def read():
    """{'status': 'missing'|'ok'|'corrupt', 'dispatch_enabled': bool|None, 'control_version': int, ...}"""
    scheduler = _scheduler()
    try:
        value = scheduler.read(NAME, None)
    except (scheduler.SchedulerError, OSError):
        return {'status': 'corrupt', 'dispatch_enabled': None, 'automation_enabled': False, 'control_version': None}
    if value is None:
        return {'status': 'missing', 'dispatch_enabled': False, 'automation_enabled': False, 'control_version': 0,
                'changed_at': None, 'changed_by': None}
    try:
        _validate(value)
    except ValueError:
        return {'status': 'corrupt', 'dispatch_enabled': None, 'automation_enabled': False, 'control_version': None}
    return dict(value, status='ok')


def dispatch_enabled():
    """True/False, or None when the control file is unreadable (callers must fail closed)."""
    return read()['dispatch_enabled']


def set_dispatch(enabled, *, changed_by=None, expected_version=None, automation=False):
    """Atomic pause/resume. Raises ControlBusy when the input lock is busy (nothing is confirmed)."""
    if automation:
        raise export_jobs.AutomationNotSupported('automation_not_supported')
    if type(enabled) is not bool:
        raise export_jobs.InvalidRequest('invalid_request')
    from .input_consistency import input_lock, ConsistencyError
    scheduler = _scheduler()
    try:
        guard = input_lock()
        guard.__enter__()
    except ConsistencyError as exc:
        raise ControlBusy() from exc
    try:
        current = read()
        if current['status'] == 'corrupt' and expected_version is None:
            raise export_jobs.StorageUnavailable('control_corrupt')
        version = current['control_version'] or 0
        if expected_version is not None and expected_version != version:
            raise ControlConflict()
        moment = datetime.fromtimestamp(export_jobs.clock(), timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
        try:
            who = changed_by or getpass.getuser()
        except Exception:
            who = 'local'
        scheduler.write(NAME, {'version': 1, 'control_version': version + 1, 'dispatch_enabled': enabled,
                                'automation_enabled': False, 'changed_at': moment, 'changed_by': who[:96]})
        return read()
    finally:
        guard.__exit__(None, None, None)
