"""Optional automatic creation of delivery jobs (Stage 4). OFF unless explicitly configured.

Automation only *creates queued delivery jobs*; it has no transport of its own. Every job it creates goes
through exactly the same path as a manual one: the executor claims it, and the atomic START qualification
(fence + control + identity + current need) still decides whether anything is sent. Automation never
creates ACK-only jobs, never touches UNKNOWN / ACK_REJECTED / active-delivery units, never retries after a
failed or uncertain attempt inside the cooldown, and stops creating jobs on any guard-rail.

Configuration: DATA_DIR/scheduler/exports-automation.json (missing or corrupt = OFF, explicit portals
required). Run state / audit summaries: DATA_DIR/scheduler/exports-automation-state.json (bounded).
Disabling it only stops creation (and cancels still-queued automation jobs); recovery and ACK-only are
independent and keep running. Importing this module performs no I/O.
"""
import getpass
import hashlib
import os
import re
from datetime import datetime, timezone

from . import export_control as control
from . import export_jobs as jobs

NAME = 'exports-automation.json'
STATE = 'exports-automation-state.json'
VERSION = 1
PORTALS = ('no', 'domiporta', 'tabelaofert', 'gruntguru')
CATEGORIES = ('new', 'update', 'withdraw')
DEFAULTS = {'categories': ['new', 'update'], 'max_per_run': 2, 'max_per_day': 10, 'max_active': 5,
            'min_interval_seconds': 900, 'cooldown_seconds': 86400, 'breaker_failures': 3}
BOUNDS = {'max_per_run': (1, 10), 'max_per_day': (1, 100), 'max_active': (1, 20), 'min_interval_seconds': (300, 86400),
          'cooldown_seconds': (3600, 7 * 86400), 'breaker_failures': (1, 10)}
KEYS = {'version', 'config_version', 'enabled', 'policy_id', 'policy_version', 'portals', 'categories', 'changed_at',
        'changed_by', *BOUNDS}
POLICY_ID = re.compile(r'^[a-z0-9][a-z0-9_-]{0,63}$')
MAX_ROWS = 500                      # at most 500 queue rows examined per run (one collection)
KEEP_RUNS = 30
ALLOWED_LAST = (None, 'ack_completed', 'transport_failed')   # anything else is unfinished or unresolved


class ConfigError(ValueError):
    code = 'invalid_automation_config'


def _scheduler():
    from InvestmentManager import scheduler_state
    return scheduler_state


def _validate(value):
    if not isinstance(value, dict) or set(value) != KEYS or value['version'] != VERSION or type(value['version']) is not int:
        raise ConfigError()
    if (type(value['config_version']) is not int or value['config_version'] < 1 or type(value['enabled']) is not bool
            or not isinstance(value['policy_id'], str) or not POLICY_ID.fullmatch(value['policy_id'])
            or type(value['policy_version']) is not int or value['policy_version'] < 1):
        raise ConfigError()
    for key, kind in (('portals', PORTALS), ('categories', CATEGORIES)):
        items = value[key]
        if (not isinstance(items, list) or not items or len(set(items)) != len(items)
                or any(not isinstance(item, str) or item not in kind for item in items)):
            raise ConfigError()
    for key, (low, high) in BOUNDS.items():
        if type(value[key]) is not int or not low <= value[key] <= high:
            raise ConfigError()
    if (not isinstance(value['changed_at'], str) or not isinstance(value['changed_by'], str)
            or len(value['changed_by']) > 96):
        raise ConfigError()
    return value


def read_config():
    """{'status': 'missing'|'ok'|'corrupt', 'enabled': bool, 'config': dict|None}. Anything but ok+enabled is OFF."""
    scheduler = _scheduler()
    try:
        value = scheduler.read(NAME, None)
    except (scheduler.SchedulerError, OSError):
        return {'status': 'corrupt', 'enabled': False, 'config': None}
    if value is None:
        return {'status': 'missing', 'enabled': False, 'config': None}
    try:
        _validate(value)
    except ConfigError:
        return {'status': 'corrupt', 'enabled': False, 'config': None}
    return {'status': 'ok', 'enabled': value['enabled'], 'config': value}


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


def _who(changed_by):
    try:
        return (changed_by or getpass.getuser())[:96]
    except Exception:
        return 'local'


def _locked_write(change):
    """Read-modify-write of the config under the non-blocking input lock (same discipline as pause/resume)."""
    from .input_consistency import input_lock, ConsistencyError
    try:
        guard = input_lock()
        guard.__enter__()
    except ConsistencyError as exc:
        raise control.ControlBusy() from exc
    try:
        current = read_config()
        value = change(current)
        _scheduler().write(NAME, value)
        return read_config()
    finally:
        guard.__exit__(None, None, None)


def enable(*, portals, categories=None, policy_id='auto', changed_by=None, **limits):
    """Turn automation on. Portals are mandatory; the policy version is bumped so slots never repeat."""
    unknown = set(limits) - set(BOUNDS)
    if unknown:
        raise ConfigError()

    def change(current):
        old = current['config'] or {}
        version = (old.get('config_version') or 0) + 1
        value = {'version': VERSION, 'config_version': version, 'enabled': True, 'policy_id': policy_id,
                 'policy_version': version, 'portals': list(portals),
                 'categories': list(categories if categories is not None else DEFAULTS['categories']),
                 'changed_at': _stamp(), 'changed_by': _who(changed_by)}
        for key in BOUNDS:
            value[key] = limits.get(key, DEFAULTS[key])
        return _validate(value)
    return _locked_write(change)


def disable(*, changed_by=None):
    """Turn automation off (idempotent). A missing/corrupt file is left OFF and rewritten as a disabled policy."""
    def change(current):
        old = current['config']
        if old is None:
            old = {'version': VERSION, 'config_version': 0, 'enabled': False, 'policy_id': 'auto', 'policy_version': 1,
                   'portals': [PORTALS[0]], 'categories': list(DEFAULTS['categories']), 'changed_at': '', 'changed_by': '',
                   **{key: DEFAULTS[key] for key in BOUNDS}}
        return _validate(dict(old, enabled=False, config_version=old['config_version'] + 1,
                              changed_at=_stamp(), changed_by=_who(changed_by)))
    return _locked_write(change)


# ------------------------------------------------------------------ state
def read_state():
    scheduler = _scheduler()
    try:
        value = scheduler.read(STATE, None)
    except (scheduler.SchedulerError, OSError):
        return {'status': 'corrupt', 'last_run_epoch': None, 'runs': []}
    if (not isinstance(value, dict) or value.get('version') != VERSION or not isinstance(value.get('runs'), list)
            or not isinstance(value.get('last_run_epoch'), (int, float))):
        return {'status': 'missing' if value is None else 'corrupt', 'last_run_epoch': None, 'runs': []}
    return {'status': 'ok', 'last_run_epoch': value['last_run_epoch'], 'runs': value['runs'][-KEEP_RUNS:]}


def _record(summary, epoch):
    """Persist a bounded audit summary. A write failure never undoes jobs already created (they are durable)."""
    state = read_state()
    runs = (state['runs'] + [summary])[-KEEP_RUNS:]
    try:
        _scheduler().write(STATE, {'version': VERSION, 'last_run_epoch': epoch, 'runs': runs})
    except Exception:
        summary['state_write'] = 'failed'


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


def _key(policy, slot, unit, action):
    text = '|'.join([policy['policy_id'], str(policy['policy_version']), slot, *map(str, unit), action])
    return hashlib.sha256(text.encode('utf-8')).hexdigest()[:32]


def skip_reason(task, active, cooled, config, destination_ok):
    """First applicable reason not to create a job for this queue row, or None. Pure; never reads I/O."""
    subject = task['subject']
    unit = (task['domain'], subject['kind'], subject['id'], task['portal'])
    if task['portal'] not in config['portals']:
        return 'portal_not_enabled'
    if task['category'] not in config['categories']:
        return 'category_not_enabled' if task['category'] != 'error' else 'queue_issue'
    if task.get('issue'):
        return 'queue_issue'
    if unit in active:
        return 'active_job'
    last = task.get('last_result')
    if last is not None and last.get('state') not in ALLOWED_LAST:
        return 'unresolved_or_unfinished_attempt'
    if unit in cooled:
        return 'cooldown'
    if not destination_ok(task):
        return 'destination_unconfigured'
    return None


def _destination_ok(task):
    from . import export_transport_config as transport_config
    try:
        return transport_config.profile_status(transport_config.profile_for(task['domain'], task['portal']))['complete']
    except transport_config.ConfigError:
        return False


def _scan(config, rows_fn):
    """Queue rows in queue order from one collection, at most MAX_ROWS; truncated flag when more rows exist."""
    from . import export_transport_config as transport_config
    settings = transport_config.company_settings() if 'gruntguru' in config['portals'] else os.environ   # .env only for GruntGuru
    page = rows_fn(max_rows=MAX_ROWS, settings=settings)
    return page['items'], page['total'] > len(page['items'])


def run(*, rows_fn=None, destination_ok=None, now=None):
    """One automation pass (called by the executor under the runner lock). Returns an audit summary."""
    configuration = read_config()
    if not configuration['enabled']:
        return reap_disabled(configuration)
    config = configuration['config']
    epoch = jobs.clock() if now is None else now
    if control.dispatch_enabled() is not True:
        return {'outcome': 'dispatch_off'}
    state = read_state()
    if state['last_run_epoch'] is not None and 0 <= epoch - state['last_run_epoch'] < config['min_interval_seconds']:
        return {'outcome': 'not_due'}
    summary = {'at': jobs.now_iso(epoch), 'config_version': config['config_version'], 'policy_id': config['policy_id'],
               'policy_version': config['policy_version'], 'created': 0, 'created_jobs': [], 'skipped': {}, 'scanned': 0}
    try:
        snap = jobs.automation_snapshot(day_since=jobs.now_iso(epoch - 86400), bad_since=jobs.now_iso(epoch - config['cooldown_seconds']))
    except jobs.JobError as exc:
        return dict(summary, outcome='error', code=exc.code)
    summary['counters'] = {key: snap[key] for key in ('pending', 'created_day', 'breaker')}
    budget = min(config['max_per_run'], config['max_per_day'] - snap['created_day'], config['max_active'] - snap['pending'])
    if snap['breaker'] >= config['breaker_failures']:
        summary['outcome'] = 'circuit_open'
    elif budget <= 0:
        summary['outcome'] = 'limit_reached'
    else:
        summary.update(_create(config, snap, budget, epoch, rows_fn, destination_ok or _destination_ok, summary))
    if summary['outcome'] != 'lock_busy':       # a busy input lock is retried on the next tick
        _record(summary, epoch)
    return summary


def _create(config, snap, budget, epoch, rows_fn, destination_ok, summary):
    if rows_fn is None:
        from . import sync_tasks
        rows_fn = sync_tasks.list_task_rows
    from .input_consistency import LockBusy
    try:
        rows, truncated = _scan(config, rows_fn)
        active = jobs.active_deliveries()
    except LockBusy:
        return {'outcome': 'lock_busy'}
    except jobs.JobError as exc:
        return {'outcome': 'error', 'code': exc.code}
    except Exception:
        return {'outcome': 'error', 'code': 'queue_unavailable'}
    slot = _slot(epoch, config['min_interval_seconds'])
    policy = {'id': config['policy_id'], 'version': config['policy_version'], 'slot': slot}
    skipped, created, stopped = summary['skipped'], [], None
    for task in rows:
        if len(created) >= budget:
            break
        reason = skip_reason(task, active, snap['cooled'], config, destination_ok)
        if reason:
            skipped[reason] = skipped.get(reason, 0) + 1
            continue
        subject = task['subject']
        intent = {'domain': task['domain'], 'subject': {'kind': subject['kind'], 'id': subject['id']}, 'portal': task['portal'],
                  'action': task['action'], 'package': {'mode': 'ensure_current'}}
        unit = (task['domain'], subject['kind'], subject['id'], task['portal'])
        try:
            receipt = jobs.create_delivery(intent, actor='policy:' + config['policy_id'], idempotency_key=_key(config, slot, unit, task['action']),
                                           dispatch_enabled=True, source='automation', policy=policy)
        except jobs.ActiveJobConflict:
            skipped['active_job'] = skipped.get('active_job', 0) + 1
            continue
        except jobs.ManualFirstRequired:                     # D09: first new job after 'not published' is manual only
            skipped['manual_first_required'] = skipped.get('manual_first_required', 0) + 1
            continue
        except (jobs.StorageLimit, jobs.DispatchPaused, jobs.StorageBusy, jobs.StorageUnavailable, jobs.SchemaUnavailable) as exc:
            stopped = exc.code
            break
        if receipt.replayed:
            skipped['already_created_in_slot'] = skipped.get('already_created_in_slot', 0) + 1
            continue
        created.append(receipt.job_id)
        active[unit] = {'job_id': receipt.job_id, 'state': 'queued'}
    outcome = 'error' if stopped else 'created' if created else 'nothing_to_do'
    result = {'outcome': outcome, 'created': len(created), 'created_jobs': created[:10], 'scanned': len(rows),
              'truncated': truncated, 'slot': slot}
    if stopped:
        result['code'] = stopped
    return result


def reap_disabled(configuration=None):
    """With automation OFF no automation job may start: cancel the ones still queued (running ones are untouched)."""
    configuration = configuration or read_config()
    if configuration['enabled']:
        return {'outcome': 'enabled'}
    try:
        queued = jobs.automation_snapshot(day_since=jobs.now_iso(0), bad_since=jobs.now_iso(0))['queued_automation']
    except jobs.JobError:
        return {'outcome': 'disabled'}
    policy = (configuration['config'] or {}).get('policy_id') or 'auto'
    cancelled = 0
    for job_id, version in queued:
        try:
            jobs.cancel_job(job_id, expected_version=version, actor='policy:' + policy)
            cancelled += 1
        except jobs.JobError:
            continue
    return {'outcome': 'disabled', 'cancelled_queued': cancelled} if cancelled else {'outcome': 'disabled'}


def status():
    configuration = read_config()
    state = read_state()
    report = {'config_status': configuration['status'], 'enabled': configuration['enabled'], 'config': configuration['config'],
              'state_status': state['status'], 'last_runs': state['runs'][-5:]}
    return report
