"""Best-effort command diagnostics, separate from command and stream outcomes."""
from concurrent.futures import CancelledError


def completion(job, future, *, emit, error_code, logger):
    # The callback must never wait for a Future or change its result on trace failure.
    try:
        record = dict(direction='WEB_TO_AI', component='runtime',
                      phase='COMMAND_RESULT_UNKNOWN', commandOutcome='UNKNOWN',
                      requestId=getattr(job, '_trace_request', None),
                      operationId=job.operation_id, cameraId=str(job.camera_id),
                      action=job.action, runId=None, observedState='UNKNOWN', error=None)
        if future.cancelled():
            record.update(phase='COMMAND_CANCELLED', commandOutcome='CANCELLED',
                          error='COMMAND_CANCELLED')
        elif not future.done():
            record['observationReason'] = 'FUTURE_NOT_DONE'
        else:
            error = future.exception()
            if error is not None:
                cancelled = isinstance(error, CancelledError)
                record.update(phase='COMMAND_CANCELLED' if cancelled else 'COMMAND_FAILED',
                              commandOutcome='CANCELLED' if cancelled else 'FAILED',
                              error='COMMAND_CANCELLED' if cancelled else error_code(error))
            else:
                result = future.result()
                group = getattr(result, 'group', result)
                if group is None:
                    record['observationReason'] = 'NO_EXECUTION_RESULT'
                else:
                    record.update(phase='COMMAND_APPLIED', commandOutcome='APPLIED')
                    observe(group, record)
        logger.info('secure_command operation=%s camera=%s action=%s outcome=%s error=%s',
                    job.operation_id, job.camera_id, job.action, record['phase'], record['error'])
        emit(**record)
    except Exception:
        # Even malformed result objects or a failed logger/sink cannot escape the callback.
        pass


def observe(group, record):
    try:
        lifecycle = getattr(group, 'lifecycle', None)
        if lifecycle is None:
            record['observationReason'] = 'NO_LIFECYCLE'
            return
        lock = lifecycle._lock
        if not lock.acquire(blocking=False):
            record['observationReason'] = 'LIFECYCLE_BUSY'
            return
        try:
            snapshot = lifecycle.snapshot()
        finally:
            lock.release()
        record.update(runId=snapshot.get('run_id'),
                      observedState=snapshot.get('observed_state') or 'UNKNOWN')
    except Exception:
        record['observationReason'] = 'STATE_UNAVAILABLE'
