"""Local delivery lifecycle for one CRM job: qualify, prepare, freeze, CREATE, qualified START,
single upload, durable result, conditional ACK. Composes existing mechanisms only.

Hard rules (D01-D09, DEC-02): the uploader runs at most once per committed START and never inside
a retry loop; retries cover attempt/job-store writes only and never cross an uncertain write
without reading the authoritative attempt first; ``result_unsaved`` is an observation, never
evidence for an ACK; a job never reports completion before the attempt says so.
Importing this module performs no I/O.
"""
from dataclasses import dataclass, field
import hashlib
import json
import os
import random
import sqlite3
import time

from . import export_arm
from . import export_attempts as attempts
from . import export_jobs as jobs
from . import export_start
from . import export_transport_config as config
from . import portal_transport

# ---- retry policy (DEC-02). Initial values; changed only in code after reviewing 2B.6 measurements.
RETRY_POLICY = {
    'start': {'attempts': 4, 'total': 10.0, 'delays': (0.25, 0.5, 1.0, 2.0)},
    'record': {'attempts': 12, 'total': 120.0, 'delays': (0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 15.0)},
    'ack': {'attempts': 8, 'total': 60.0, 'delays': (0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 15.0)},
    'advance': {'attempts': 5, 'total': 20.0, 'delays': (0.5, 1.0, 2.0, 4.0)},
    'read': {'attempts': 5, 'total': 15.0, 'delays': (0.5, 1.0, 2.0, 4.0)},
}
OK_DOMESTIC = {'current', 'verified', 'prepared_verified'}
OK_FOREIGN = {'prepared', 'verified', 'skipped_current'}
WAITING = {'lock_busy', 'budget_exhausted', 'network_timeout'}


class Stop(Exception):
    """Controlled end of a job: state + safe reason (+ optional details)."""

    def __init__(self, state, reason, *, phase=None, details=None):
        super().__init__(reason)
        self.state, self.reason, self.phase, self.details = state, reason, phase, details or {}


class StorageFailure(Exception):
    """A critical coordination write could not be persisted: the job stays running (recovered later)."""


@dataclass
class Env:
    secret_getter: object = None
    transport: object = None
    settings: object = None             # callable(domain) -> settings mapping or None
    sleep: object = time.sleep
    clock: object = time.monotonic
    rng: object = random.random
    policy: dict = field(default_factory=lambda: RETRY_POLICY)
    hooks: dict = field(default_factory=dict)   # test seams: name -> callable(), also used for kill points

    def hook(self, name):
        action = self.hooks.get(name)
        if action is not None:
            action()


def default_env():
    return Env(secret_getter=config.environment_getter, transport=portal_transport,
               settings=_environment_settings)


def _environment_settings(domain):
    if domain == 'foreign':
        # Cron intentionally does not load the whole application .env. Read only
        # the foreign producer input that is explicitly allow-listed by the same
        # lazy getter as transport settings, so WSGI and the worker fingerprint
        # an identical package context.
        settings = {key: config.environment_getter(key) for key in config.FOREIGN_PACKAGE_KEYS}
        pins = settings.get('FOREIGN_MEDIA_HOST_PINS')
        if isinstance(pins, str):
            try:
                settings['FOREIGN_MEDIA_HOST_PINS'] = json.loads(pins)
            except ValueError:
                pass  # the existing verifier rejects malformed configuration
        return settings
    return {key: os.environ.get(key) for key in config.COMPANY_KEYS}


def _settings(env, claim):
    """Company settings for package preparation. Only a GruntGuru job (the one portal that uses them) may fall back to the
    .env file, and only for the company keys; every other job never opens the file for this purpose."""
    settings = env.settings(claim.domain) if env.settings else None
    if settings is not None and claim.portal == 'gruntguru' and env.settings is _environment_settings:
        settings = {key: value or config.environment_getter(key) for key, value in settings.items()}
    return settings


@dataclass(frozen=True)
class PackageSnapshot:
    package_id: str
    zip_filename: str
    zip_bytes: bytes
    manifest_bytes: bytes
    binding: dict
    binding_sha256: str


@dataclass
class DeliveryOutcome:
    job_state: str
    reason: object
    attempt_id: object = None
    attempt_state: object = None
    ftp_status: str = 'not_started'
    ack_status: str = 'not_started'
    uploader_calls: int = 0
    detail: dict = field(default_factory=dict)


# ------------------------------------------------------------------ retries
def is_busy(exc):
    """True for a known chance-of-retry condition raised BEFORE any write (lock/SQLite busy)."""
    from .input_consistency import LockBusy
    from . import domestic_batch_limits as limits
    seen = set()
    while exc is not None and id(exc) not in seen:
        seen.add(id(exc))
        if isinstance(exc, (LockBusy, jobs.StorageBusy)):
            return True
        if isinstance(exc, limits.BatchStop) and exc.code == 'lock_busy':
            return True
        if isinstance(exc, sqlite3.OperationalError):
            code = getattr(exc, 'sqlite_errorcode', 0) & 255
            if code in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED) or 'locked' in str(exc).lower():
                return True
        exc = exc.__cause__ or exc.__context__
    return False


def _delay(env, kind, number):
    delays = env.policy[kind]['delays']
    base = delays[min(number, len(delays) - 1)]
    return max(0.0, base * (0.8 + 0.4 * env.rng()))


def retry_busy(env, kind, function):
    """Run `function` again only while it fails with a busy condition; other errors propagate at once."""
    policy = env.policy[kind]
    started, number = env.clock(), 0
    while True:
        try:
            return function()
        except Exception as exc:
            if not is_busy(exc):
                raise
            number += 1
            if number >= policy['attempts'] or env.clock() - started >= policy['total']:
                raise
            env.sleep(_delay(env, kind, number - 1))


# ------------------------------------------------------------------ job store
def _advance(env, claim, *, critical=True, **kwargs):
    try:
        return retry_busy(env, 'advance', lambda: jobs.advance(claim, **kwargs))
    except jobs.ClaimLost:
        raise
    except Exception as exc:
        if critical:
            raise StorageFailure('advance_failed') from exc
        return claim


def _phase(env, claim, phase, **kwargs):
    return _advance(env, claim, phase=phase, **kwargs)


# ------------------------------------------------------------------ attempt access
def _read_attempt(env, claim, attempt_id=None, *, anchor=None, portal=None):
    """Authoritative read with retries; returns the observation dict."""
    attempt_id = attempt_id or claim.attempt_id or claim.planned_attempt_id
    policy = env.policy['read']
    started, number = env.clock(), 0
    while True:
        observation = attempts.inspect_attempt(attempt_id, anchor_id=anchor if anchor is not None else claim.attempt_anchor_id,
                                               portal=portal or claim.portal, domain=claim.domain)
        if observation['state'] != 'unavailable':
            return observation
        number += 1
        if number >= policy['attempts'] or env.clock() - started >= policy['total']:
            return observation
        env.sleep(_delay(env, 'read', number - 1))


def _refresh_dictionaries(claim, portal):
    if claim.domain == 'domestic':
        from .domestic_dictionaries import dictionary_inputs
        dictionary_inputs(portal)


def _unit(claim):
    return {'domain': claim.domain, 'subject': {'kind': claim.subject_kind, 'id': claim.subject_id},
            'portal': claim.portal, 'action': claim.action}


# ------------------------------------------------------------------ qualification / package
def qualify(claim, env):
    from . import sync_tasks
    try:
        return retry_busy(env, 'start', lambda: sync_tasks.qualify_unit_snapshot(_unit(claim)))
    except Exception as exc:
        if is_busy(exc):
            raise Stop('queued', 'lock_busy', phase='waiting_resource') from exc
        raise Stop('blocked', 'qualification_unavailable') from exc


def _check_need(claim, q):
    if not q.required:
        raise Stop('completed', 'no_action')
    if q.action != claim.action:
        raise Stop('blocked', 'qualification_changed')
    if q.blocking:
        import re
        raise Stop('blocked', q.blocking[0] if re.fullmatch(r'[a-z0-9_]{1,64}', q.blocking[0]) else 'qualification_blocked')


def ensure_package(claim, env):
    """Package id for this job: fixed once saved; `existing` uses exactly that id; else prepare/use current."""
    if claim.package_id:
        return claim.package_id
    if claim.package_mode == 'existing':
        return claim.requested_package_id
    settings = _settings(env, claim)
    if claim.domain == 'domestic':
        from . import domestic_batch, domestic_sets as sets, domestic_package_catalog as catalog
        result = domestic_batch.process_offer(claim.subject_id, settings=settings)
        row = next((item for item in result.get('sets', []) if item.get('action') == claim.action), None)
        code = (row or result).get('code')
        if row is None:
            if result.get('code') == 'no_action':
                raise Stop('completed', 'no_action')
            if code in WAITING:
                raise Stop('queued', code, phase='waiting_resource')
            raise Stop('blocked', _safe_code(code))
        if code in WAITING:
            raise Stop('queued', code, phase='waiting_resource')
        if code not in OK_DOMESTIC:
            raise Stop('blocked', _safe_code(code))
        _, base = catalog._root()
        pointer = sets.current(base, claim.subject_id, claim.action)
        package_id = pointer['packages'].get(claim.portal) if pointer else None
        if not package_id:
            raise Stop('blocked', 'package_missing')
        return package_id
    from . import foreign_batch
    result = foreign_batch.process_unit((claim.subject_kind, claim.subject_id, claim.portal, claim.action), settings=settings)
    outcome = result.get('outcome')
    if outcome == 'no_action':
        raise Stop('completed', 'no_action')
    if outcome not in OK_FOREIGN or not result.get('package_id'):
        raise Stop('blocked', _safe_code(result.get('reason') or outcome))
    return result['package_id']


def _safe_code(value):
    import re
    text = str(value or 'preparation_failed').lower().replace('-', '_')
    text = re.sub(r'[^a-z0-9_]', '_', text)[:64]
    return text or 'preparation_failed'


def freeze_package(claim, package_id, env):
    """Verify the package (READY) and copy its exact bytes into the process. No persistent cache."""
    from . import domestic_package_catalog as catalog
    from .input_consistency import input_lock
    settings = _settings(env, claim)
    try:
        if claim.domain == 'domestic':
            from . import domestic_sets as sets
            _refresh_dictionaries(claim, claim.portal)
            lock = sets.locked
        else:
            lock = input_lock
        with lock():
            if claim.domain == 'domestic':
                token = attempts._domain.set('domestic')
                try:
                    binding = attempts._package(package_id, settings)
                finally:
                    attempts._domain.reset(token)
                _, base = catalog._root()
                folder = catalog.package_folder(base, package_id)
            else:
                from .foreign_attempt_inputs import package as foreign_package
                binding = foreign_package(package_id, settings)
                _, base = catalog._root('foreign')
                folder = base / package_id
            with catalog._open(folder / 'manifest.json', base) as stream:
                manifest = stream.read(catalog.MAX_MANIFEST + 1)
            with catalog._open(folder / binding['zip_name'], base) as stream:
                body = stream.read(catalog.MAX_ZIP + 1)
    except attempts.AttemptError as exc:
        raise Stop('blocked', 'package_not_ready') from exc
    except Exception as exc:
        if is_busy(exc):
            raise Stop('queued', 'lock_busy', phase='waiting_resource') from exc
        raise Stop('blocked', 'package_unavailable') from exc
    if (len(manifest) > catalog.MAX_MANIFEST or not 0 < len(body) <= catalog.MAX_ZIP
            or len(body) != binding['zip_size'] or hashlib.sha256(body).hexdigest() != binding['zip_sha256']
            or hashlib.sha256(manifest).hexdigest() != binding['manifest_sha256']):
        raise Stop('blocked', 'package_changed')
    return PackageSnapshot(package_id, binding['zip_name'], body, manifest, binding, jobs.binding_digest(binding))


# ------------------------------------------------------------------ attempt writes
def _create(claim, snapshot, env):
    settings = _settings(env, claim)
    attempt_id = claim.attempt_id or claim.planned_attempt_id
    binding = snapshot.binding

    def call():
        _refresh_dictionaries(claim, claim.portal)
        if claim.domain == 'domestic':
            return attempts.create_attempt(snapshot.package_id, claim.subject_id, claim.portal, claim.action,
                                           attempt_id=attempt_id, settings=settings)
        return attempts.create_attempt(snapshot.package_id, portal=claim.portal, action=claim.action,
                                       attempt_id=attempt_id, subject=binding['subject'], settings=settings,
                                       domain='foreign')
    try:
        return retry_busy(env, 'start', call)
    except Exception as exc:
        if is_busy(exc):
            raise Stop('queued', 'lock_busy', phase='waiting_resource') from exc
        if isinstance(exc, attempts.AttemptError):
            raise Stop('blocked', 'create_refused') from exc
        observation = _read_attempt(env, claim, attempt_id, anchor=binding['offer_id'])
        if observation['state'] == 'found':           # CREATE committed, reply lost: adopt the durable attempt
            return observation['attempt']
        if observation['state'] == 'absent':
            raise Stop('queued', 'create_uncertain', phase='waiting_resource') from exc
        raise Stop('needs_review', 'attempt_unreadable') from exc


def _start(claim, snapshot, item, env):
    """Qualified START with retries; returns the decision dict (can_send decides everything)."""
    settings = _settings(env, claim)
    policy = env.policy['start']
    started, number = env.clock(), 0
    while True:
        try:
            _refresh_dictionaries(claim, claim.portal)
            return export_start.start_qualified_transport(item['attempt_id'], snapshot.binding, job_claim=claim,
                                                      settings=settings, domain=claim.domain)
        except Exception as exc:
            busy = is_busy(exc)
            if not busy:
                observation = _read_attempt(env, claim, item['attempt_id'], anchor=snapshot.binding['offer_id'])
                state = observation['attempt']['state'] if observation['state'] == 'found' else observation['state']
                if state == 'prepared':
                    pass                               # the START did not commit; a retry is safe
                elif state == 'transport_unknown':
                    raise Stop('needs_review', 'start_uncertain') from exc
                else:
                    raise Stop('needs_review', 'attempt_unreadable' if state in ('unavailable', 'inconsistent', 'absent')
                               else 'start_uncertain') from exc
            number += 1
            if number >= policy['attempts'] or env.clock() - started >= policy['total']:
                raise Stop('queued', 'lock_busy' if busy else 'start_uncertain', phase='waiting_resource') from exc
            env.sleep(_delay(env, 'start', number - 1))


START_REFUSALS = {
    'dispatch_paused': ('queued', 'paused'), 'control_unavailable': ('queued', 'waiting_resource'),
    'no_longer_required': ('completed', None),
}


def _record(claim, snapshot, attempt_id, desired_state, outcome, env):
    """record_transport_result with bounded retries. Returns the authoritative attempt item or None."""
    policy = env.policy['record']
    started, number = env.clock(), 0
    while True:
        try:
            return attempts.record_transport_result(attempt_id, snapshot.binding, outcome, domain=claim.domain)
        except Exception as exc:
            busy = is_busy(exc)
            if not busy:
                observation = _read_attempt(env, claim, attempt_id, anchor=snapshot.binding['offer_id'])
                if observation['state'] == 'found':
                    item = observation['attempt']
                    if item['state'] != 'transport_unknown':
                        return item                    # target (or another final state) is already durable
                    # still UNKNOWN: the write did not commit, retrying is safe
            number += 1
            if number >= policy['attempts'] or env.clock() - started >= policy['total']:
                return None
            env.sleep(_delay(env, 'record', number - 1))


def _ack(claim, snapshot, attempt_id, env):
    """Conditional ACK with bounded retries. Returns the attempt item (state may be ack_*), or None."""
    settings = _settings(env, claim)
    policy = env.policy['ack']
    started, number = env.clock(), 0
    while True:
        try:
            _refresh_dictionaries(claim, claim.portal)
            return attempts.acknowledge_attempt(attempt_id, snapshot.binding, settings=settings, domain=claim.domain)
        except Exception as exc:
            if not is_busy(exc):
                observation = _read_attempt(env, claim, attempt_id, anchor=snapshot.binding['offer_id'])
                if observation['state'] == 'found' and observation['attempt']['state'] in ('ack_completed', 'ack_rejected'):
                    return observation['attempt']
            number += 1
            if number >= policy['attempts'] or env.clock() - started >= policy['total']:
                return None
            env.sleep(_delay(env, 'ack', number - 1))


# ------------------------------------------------------------------ the lifecycle
def execute_delivery(claim, env=None):
    """Run one delivery job to a durable end state. Raises jobs.ClaimLost / StorageFailure only."""
    env = env or default_env()
    metrics, state = {}, {'calls': 0}
    outcome = DeliveryOutcome('failed', 'unexpected')

    def timed(name, function):
        started = time.perf_counter()
        try:
            return function()
        finally:
            metrics[name] = {'seconds': round(time.perf_counter() - started, 6)}

    try:
        outcome = _lifecycle(claim, env, metrics, state, timed)
    except Stop as stop:
        outcome = DeliveryOutcome(stop.state, stop.reason, detail=stop.details)
        outcome.attempt_id = state.get('attempt_id')
        outcome.uploader_calls = state['calls']
        outcome.detail = dict(stop.details, phase=stop.phase)
        return _finalize(claim, env, outcome, metrics, state, stop)
    return _finalize(claim, env, outcome, metrics, state, None)


def _finalize(claim, env, outcome, metrics, state, stop):
    env.hook('before_finish')
    current = state.get('claim', claim)
    details = {k: v for k, v in (outcome.detail or {}).items() if v is not None}
    for key in ('attempt_state', 'ftp_status', 'ack_status'):
        value = getattr(outcome, key)
        if value not in (None, 'not_started'):
            details[key] = value
    if outcome.job_state == 'queued':
        _advance(env, current, state='queued', phase=details.get('phase') or 'waiting_resource',
                 reason_code=outcome.reason, details=details, metrics=metrics)
    else:
        _advance(env, current, state=outcome.job_state, reason_code=outcome.reason, details=details, metrics=metrics)
    return outcome


def _lifecycle(claim, env, metrics, state, timed):
    domain = claim.domain
    try:
        profile = config.profile_for(domain, claim.portal)
    except config.ConfigError as exc:
        raise Stop('blocked', exc.code) from exc
    missing = config.missing_keys(profile, env.secret_getter or config.environment_getter)
    if missing:
        raise Stop('blocked', 'config_missing', details={'missing': missing})
    if env.transport is portal_transport:                    # the real network transport (never a test double)
        verdict = export_arm.check(profile)
        if not verdict['allowed']:                           # refuse BEFORE any attempt/START exists; the uploader checks again
            export_arm.refuse(profile, verdict['code'])
            raise Stop('blocked', 'transport_not_armed', details={'arm': verdict['code']})
    env.hook('after_claim')
    claim = state['claim'] = _phase(env, claim, 'qualification')
    _check_need(claim, timed('qualification', lambda: qualify(claim, env)))
    env.hook('after_qualification')
    claim = state['claim'] = _phase(env, claim, 'preparation')
    package_id = timed('preparation', lambda: ensure_package(claim, env))
    env.hook('after_preparation')
    claim = state['claim'] = _phase(env, claim, 'snapshot')
    snapshot = timed('snapshot', lambda: freeze_package(claim, package_id, env))
    env.hook('after_snapshot')
    if claim.binding_sha256 and claim.binding_sha256 != snapshot.binding_sha256:
        raise Stop('blocked', 'package_changed')
    references = {}
    if claim.package_id is None:
        references['package_id'] = snapshot.package_id
    if claim.binding_sha256 is None:
        references['binding_sha256'] = snapshot.binding_sha256
    if claim.attempt_anchor_id is None:
        references['attempt_anchor_id'] = snapshot.binding['offer_id']
    claim = state['claim'] = _advance(env, claim, phase='create_requested', references=references)
    env.hook('before_create')
    item = timed('create', lambda: _create(claim, snapshot, env))
    env.hook('after_create_commit')
    state['attempt_id'] = item['attempt_id']
    if item['binding'] != snapshot.binding:
        raise Stop('blocked', 'binding_mismatch')
    claim = state['claim'] = _advance(env, claim, phase='attempt_linked', references={
        'attempt_id': item['attempt_id'], 'observed_attempt_event_id': item['event_id']})
    env.hook('after_create')
    if item['state'] == 'ack_completed':
        # CREATE returned an earlier ACK for the same binding. Only no longer needing the operation completes the job.
        again = qualify(claim, env)
        if not again.required:
            raise Stop('completed', 'already_acknowledged')
        raise Stop('blocked', 'manual_preparation_required')
    if item['state'] != 'prepared':
        raise Stop('needs_review', 'attempt_state_unexpected', details={'attempt_state': item['state']})
    claim = state['claim'] = _advance(env, claim, phase='start_requested')
    env.hook('before_start')
    decision = timed('start', lambda: _start(claim, snapshot, item, env))
    env.hook('after_start')
    if decision.get('can_send') is not True:
        _handle_refusal(decision)
    # ---- permission granted: no job write, no file read, nothing between here and the uploader
    state['calls'] += 1
    try:
        result = env.transport.upload_portal_zip(profile, snapshot.zip_filename, snapshot.zip_bytes,
                                                 secret_getter=env.secret_getter or config.environment_getter)
    except Exception:
        result = portal_transport.UploadResult('unknown', 'stor', error_code='unknown')
    env.hook('after_upload')
    for name, value in result.timings.items():
        metrics['ftp_' + name] = value
    metrics['ftp'] = {'bytes_sent': result.bytes_sent, 'bytes_complete': result.bytes_complete}
    info = {'phase': result.phase, 'error_code': result.error_code, 'bytes_sent': result.bytes_sent,
            'stor_reply_code': result.stor_reply_code, 'rename_reply_code': result.rename_reply_code}
    outcome = DeliveryOutcome('needs_review', 'transport_unknown', item['attempt_id'], 'transport_unknown',
                              'unknown', 'not_started', state['calls'], info)
    state['claim'] = _advance(env, claim, phase='transport', critical=False)
    claim = state['claim']
    if result.outcome == 'unknown':
        return outcome
    desired = 'transport_confirmed' if result.outcome == 'confirmed' else 'transport_failed'
    recorded = timed('record', lambda: _record(claim, snapshot, item['attempt_id'], desired,
                                              'confirmed' if result.outcome == 'confirmed' else 'failed', env))
    env.hook('after_record')
    if recorded is None:
        _observe_unsaved(env, claim, result)
        outcome.reason, outcome.ftp_status = 'result_unsaved', 'confirmed' if result.outcome == 'confirmed' else 'failed_before_send'
        outcome.detail['observed'] = result.outcome
        return outcome
    outcome.attempt_state = recorded['state']
    if result.outcome == 'not_sent':
        if recorded['state'] == 'transport_failed':
            return DeliveryOutcome('failed', 'transport_failed', item['attempt_id'], 'transport_failed',
                                   'failed_before_send', 'not_started', state['calls'], info)
        outcome.reason, outcome.ftp_status = 'result_conflict', 'failed_before_send'
        return outcome
    outcome.ftp_status = 'confirmed'
    if recorded['state'] == 'ack_completed':
        return DeliveryOutcome('completed', 'ack_completed', item['attempt_id'], 'ack_completed', 'confirmed', 'completed',
                               state['calls'], info)
    if recorded['state'] not in ('transport_confirmed', 'ack_failed'):
        outcome.reason, outcome.attempt_state = 'result_conflict', recorded['state']
        return outcome
    state['claim'] = _advance(env, claim, phase='ack_requested', critical=False)
    claim = state['claim']
    acked = timed('ack', lambda: _ack(claim, snapshot, item['attempt_id'], env))
    env.hook('after_ack')
    if acked is None:
        outcome.reason, outcome.ack_status = 'ack_pending', 'pending'
        return outcome
    outcome.attempt_state = acked['state']
    if acked['state'] == 'ack_completed':
        return DeliveryOutcome('completed', 'ack_completed', item['attempt_id'], 'ack_completed', 'confirmed', 'completed',
                               state['calls'], info)
    outcome.reason = 'ack_rejected' if acked['state'] == 'ack_rejected' else 'ack_pending'
    outcome.ack_status = 'rejected' if acked['state'] == 'ack_rejected' else 'failed'
    return outcome


def _handle_refusal(decision):
    reason = decision.get('reason')
    if reason in ('claim_lost', 'job_missing'):
        raise jobs.ClaimLost('claim_lost')
    if reason is None:
        raise Stop('needs_review', 'attempt_state_changed', details={'attempt_state': decision.get('state')})
    if reason in START_REFUSALS:
        state, phase = START_REFUSALS[reason]
        if state == 'completed':
            raise Stop('completed', 'no_action')
        raise Stop(state, reason, phase=phase)
    raise Stop('blocked', _safe_code(reason))


def _observe_unsaved(env, claim, result):
    try:
        retry_busy(env, 'advance', lambda: jobs.observe(claim, 'result_unsaved', reason_code='result_unsaved',
                                                         details={'observed': result.outcome, 'observation_only': True}))
    except Exception:
        pass


# ------------------------------------------------------------------ ACK-only
def execute_ack_only(claim, env=None):
    """ACK recovery: read the attempt, repeat ONLY the conditional ACK. Never prepares, creates, starts or uploads."""
    env = env or default_env()
    metrics = {}
    outcome = _ack_only(claim, env, metrics)
    details = {k: v for k, v in {'attempt_state': outcome.attempt_state, 'ack_status': outcome.ack_status}.items()
               if v not in (None, 'not_started')}
    if outcome.job_state == 'queued':
        _advance(env, claim, state='queued', phase='waiting_resource', reason_code=outcome.reason, details=details,
                 metrics=metrics)
    else:
        _advance(env, claim, state=outcome.job_state, reason_code=outcome.reason, details=details, metrics=metrics)
        if outcome.job_state == 'completed' and claim.parent_job_id:
            try:
                jobs.complete_review(claim.parent_job_id, reason_code='recovered_by_ack_only',
                                     details={'ack_job': claim.job_id})
            except jobs.JobError:
                pass
    return outcome


def _ack_only(claim, env, metrics):
    started = time.perf_counter()
    observation = _read_attempt(env, claim, claim.attempt_id, anchor=claim.attempt_anchor_id)
    metrics['read'] = {'seconds': round(time.perf_counter() - started, 6)}
    code = observation['state']
    if code == 'unavailable':
        return DeliveryOutcome('queued', 'attempt_unreadable')
    if code == 'inconsistent':
        return DeliveryOutcome('needs_review', 'history_inconsistent')
    if code == 'absent':
        return DeliveryOutcome('blocked', 'attempt_not_found')
    item = observation['attempt']
    base = DeliveryOutcome('blocked', 'ack_not_recoverable', item['attempt_id'], item['state'])
    if claim.binding_sha256 and jobs.binding_digest(item['binding']) != claim.binding_sha256:
        return DeliveryOutcome('needs_review', 'binding_changed', item['attempt_id'], item['state'])
    if item['state'] == 'ack_completed':
        return DeliveryOutcome('completed', 'already_acknowledged', item['attempt_id'], 'ack_completed', 'confirmed', 'completed')
    if item['state'] in ('transport_unknown', 'ack_rejected'):
        base.job_state = 'needs_review'
        return base
    if item['state'] not in ('transport_confirmed', 'ack_failed'):
        return base
    snapshot = PackageSnapshot(item['binding']['package_id'], item['binding']['zip_name'], b'', b'', item['binding'],
                               jobs.binding_digest(item['binding']))
    ack_started = time.perf_counter()
    acked = _ack(claim, snapshot, item['attempt_id'], env)
    metrics['ack'] = {'seconds': round(time.perf_counter() - ack_started, 6)}
    if acked is None:
        return DeliveryOutcome('needs_review', 'ack_pending', item['attempt_id'], item['state'], 'confirmed', 'pending')
    if acked['state'] == 'ack_completed':
        return DeliveryOutcome('completed', 'ack_completed', item['attempt_id'], 'ack_completed', 'confirmed', 'completed')
    return DeliveryOutcome('needs_review', 'ack_rejected' if acked['state'] == 'ack_rejected' else 'ack_pending',
                           item['attempt_id'], acked['state'], 'confirmed',
                           'rejected' if acked['state'] == 'ack_rejected' else 'failed')
