"""Durable export job store (DDL v1.1): intent, claim, cancel and audit.

Coordination only. Transport state stays in the existing export attempts
(``export_attempt_v1/v2``). Importing this module performs no I/O; schema
migration happens only in the explicit :func:`init_schema`.
"""
from contextlib import closing, contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timezone
import base64
import hashlib
import json
import os
import re
import sqlite3
import time
import uuid

from modules.core import storage_paths

SCHEMA_VERSION = 1
MiB = 1024 * 1024
WARN_BYTES = 40 * MiB      # warning when physical size is above
BLOCK_BYTES = 48 * MiB     # new deliveries refused when physical size is at/above
MAX_EVENTS = 100000        # mirrors integrator.sync_tasks.MAX_EVENTS (asserted by tests)
HTTP_TIMEOUT = 1.0
WORKER_TIMEOUT = 5.0
MAX_EVENT_RESPONSE_BYTES = 1024 * 1024

DDL = r'''
CREATE TABLE export_jobs (
    job_id TEXT PRIMARY KEY NOT NULL
        CHECK(length(job_id)=32 AND job_id NOT GLOB '*[^0-9a-f]*'),
    seq INTEGER NOT NULL UNIQUE CHECK(typeof(seq)='integer' AND seq>0),
    schema_version INTEGER NOT NULL DEFAULT 1 CHECK(schema_version=1),
    kind TEXT NOT NULL CHECK(kind IN ('delivery','ack_only')),
    domain TEXT NOT NULL CHECK(domain IN ('domestic','foreign')),
    subject_kind TEXT NOT NULL,
    subject_id INTEGER NOT NULL
        CHECK(typeof(subject_id)='integer' AND subject_id>0),
    portal TEXT NOT NULL,
    action TEXT NOT NULL CHECK(action IN ('add','delete')),
    source TEXT NOT NULL CHECK(source IN ('manual','automation')),
    actor_ref TEXT NOT NULL CHECK(length(actor_ref) BETWEEN 1 AND 96),
    idempotency_key TEXT NOT NULL
        CHECK(length(idempotency_key)=32 AND idempotency_key NOT GLOB '*[^0-9a-f]*'),
    request_json TEXT NOT NULL CHECK(length(CAST(request_json AS BLOB))<=2048),
    request_sha256 TEXT NOT NULL
        CHECK(length(request_sha256)=64 AND request_sha256 NOT GLOB '*[^0-9a-f]*'),
    batch_id TEXT CHECK(batch_id IS NULL OR
        (length(batch_id)=32 AND batch_id NOT GLOB '*[^0-9a-f]*')),
    policy_id TEXT CHECK(policy_id IS NULL OR length(policy_id) BETWEEN 1 AND 96),
    policy_version INTEGER CHECK(policy_version IS NULL OR policy_version>0),
    slot_key TEXT CHECK(slot_key IS NULL OR length(slot_key) BETWEEN 1 AND 64),
    package_mode TEXT NOT NULL CHECK(package_mode IN ('ensure_current','existing','none')),
    requested_package_id TEXT CHECK(requested_package_id IS NULL OR
        (length(requested_package_id)=32 AND requested_package_id NOT GLOB '*[^0-9a-f]*')),
    package_id TEXT CHECK(package_id IS NULL OR
        (length(package_id)=32 AND package_id NOT GLOB '*[^0-9a-f]*')),
    planned_attempt_id TEXT CHECK(planned_attempt_id IS NULL OR
        (length(planned_attempt_id)=32 AND planned_attempt_id NOT GLOB '*[^0-9a-f]*')),
    attempt_id TEXT CHECK(attempt_id IS NULL OR
        (length(attempt_id)=32 AND attempt_id NOT GLOB '*[^0-9a-f]*')),
    binding_sha256 TEXT CHECK(binding_sha256 IS NULL OR
        (length(binding_sha256)=64 AND binding_sha256 NOT GLOB '*[^0-9a-f]*')),
    attempt_anchor_id INTEGER CHECK(attempt_anchor_id IS NULL OR
        (typeof(attempt_anchor_id)='integer' AND attempt_anchor_id>0)),
    observed_attempt_event_id INTEGER CHECK(observed_attempt_event_id IS NULL OR observed_attempt_event_id>0),
    parent_job_id TEXT REFERENCES export_jobs(job_id) ON DELETE RESTRICT,
    state TEXT NOT NULL CHECK(state IN
        ('queued','running','completed','blocked','failed','needs_review','cancelled')),
    phase TEXT NOT NULL CHECK(phase IN
        ('accepted','claimed','qualification','preparation','snapshot','create_requested',
         'attempt_linked','start_requested','transport','result_recorded','ack_requested',
         'recovery','waiting_resource','paused','finished')),
    reason_code TEXT CHECK(reason_code IS NULL OR
        (length(reason_code) BETWEEN 1 AND 64 AND reason_code NOT GLOB '*[^a-z0-9_]*')),
    row_version INTEGER NOT NULL DEFAULT 1 CHECK(row_version>0),
    claim_version INTEGER NOT NULL DEFAULT 0 CHECK(claim_version>=0),
    owner_id TEXT CHECK(owner_id IS NULL OR
        (length(owner_id)=32 AND owner_id NOT GLOB '*[^0-9a-f]*')),
    recovery_attempts INTEGER NOT NULL DEFAULT 0
        CHECK(typeof(recovery_attempts)='integer' AND recovery_attempts BETWEEN 0 AND 1000),
    recovery_first_at TEXT,
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    started_at TEXT,
    finished_at TEXT,
    metrics_json TEXT NOT NULL DEFAULT '{}'
        CHECK(length(CAST(metrics_json AS BLOB))<=65536),
    CHECK(
        (domain='domestic' AND subject_kind='offer'
         AND portal IN ('no','domiporta','tabelaofert','gruntguru'))
        OR (domain='foreign' AND subject_kind='foreign_offer'
            AND portal IN ('domiporta','tabelaofert'))
        OR (domain='foreign' AND subject_kind='cyprus_development'
            AND portal='tabelaofert' AND action='add')
    ),
    CHECK(
        (source='manual' AND policy_id IS NULL AND policy_version IS NULL AND slot_key IS NULL)
        OR (source='automation' AND policy_id IS NOT NULL AND policy_version IS NOT NULL AND slot_key IS NOT NULL)
    ),
    CHECK(
        (kind='delivery' AND planned_attempt_id IS NOT NULL AND package_mode IN ('ensure_current','existing'))
        OR (kind='ack_only' AND source='manual' AND planned_attempt_id IS NULL
            AND package_mode='none' AND attempt_id IS NOT NULL AND package_id IS NOT NULL
            AND binding_sha256 IS NOT NULL AND attempt_anchor_id IS NOT NULL)
    ),
    CHECK((package_mode='existing' AND requested_package_id IS NOT NULL)
          OR (package_mode<>'existing' AND requested_package_id IS NULL)),
    CHECK((state='running' AND owner_id IS NOT NULL AND claim_version>0 AND started_at IS NOT NULL)
          OR (state<>'running' AND owner_id IS NULL)),
    CHECK((state IN ('queued','running') AND finished_at IS NULL)
          OR (state IN ('completed','blocked','failed','needs_review','cancelled') AND finished_at IS NOT NULL)),
    CHECK(attempt_id IS NULL OR (package_id IS NOT NULL AND binding_sha256 IS NOT NULL AND attempt_anchor_id IS NOT NULL)),
    CHECK((kind='delivery' AND parent_job_id IS NULL) OR kind='ack_only'),
    CHECK(parent_job_id IS NULL OR parent_job_id<>job_id),
    CHECK(package_mode<>'existing' OR package_id IS NULL OR package_id=requested_package_id),
    CHECK(state IN ('queued','running') OR phase='finished'),
    CHECK((recovery_attempts=0)=(recovery_first_at IS NULL)),
    UNIQUE(actor_ref,source,idempotency_key)
);

CREATE UNIQUE INDEX export_jobs_planned_attempt
    ON export_jobs(domain,planned_attempt_id) WHERE planned_attempt_id IS NOT NULL;
CREATE UNIQUE INDEX export_jobs_active_delivery
    ON export_jobs(domain,subject_kind,subject_id,portal)
    WHERE kind='delivery' AND state IN ('queued','running','needs_review');
CREATE UNIQUE INDEX export_jobs_active_ack
    ON export_jobs(domain,attempt_id)
    WHERE kind='ack_only' AND state IN ('queued','running');
CREATE UNIQUE INDEX export_jobs_auto_slot
    ON export_jobs(policy_id,policy_version,slot_key,domain,subject_kind,subject_id,portal,action)
    WHERE source='automation' AND kind='delivery';
CREATE INDEX export_jobs_dispatch ON export_jobs(kind,state,seq);
CREATE INDEX export_jobs_attempt ON export_jobs(domain,attempt_id);
CREATE INDEX export_jobs_batch ON export_jobs(batch_id,seq);
CREATE INDEX export_jobs_parent ON export_jobs(parent_job_id);

CREATE TABLE export_job_events (
    event_id INTEGER PRIMARY KEY AUTOINCREMENT,
    job_id TEXT NOT NULL REFERENCES export_jobs(job_id) ON DELETE RESTRICT,
    job_version INTEGER NOT NULL CHECK(job_version>0),
    event_type TEXT NOT NULL CHECK(event_type IN
        ('accepted','claimed','phase_changed','attempt_linked','resource_wait','dispatch_paused',
         'completed','blocked','failed','needs_review','cancelled','recovered','metrics_incomplete',
         'recovery_deferred','result_unsaved')),
    actor_ref TEXT NOT NULL CHECK(length(actor_ref) BETWEEN 1 AND 96),
    claim_version INTEGER NOT NULL CHECK(claim_version>=0),
    from_state TEXT CHECK(from_state IS NULL OR from_state IN
        ('queued','running','completed','blocked','failed','needs_review','cancelled')),
    to_state TEXT NOT NULL CHECK(to_state IN
        ('queued','running','completed','blocked','failed','needs_review','cancelled')),
    phase TEXT NOT NULL CHECK(phase IN
        ('accepted','claimed','qualification','preparation','snapshot','create_requested',
         'attempt_linked','start_requested','transport','result_recorded','ack_requested',
         'recovery','waiting_resource','paused','finished')),
    reason_code TEXT CHECK(reason_code IS NULL OR
        (length(reason_code) BETWEEN 1 AND 64 AND reason_code NOT GLOB '*[^a-z0-9_]*')),
    details_json TEXT NOT NULL DEFAULT '{}'
        CHECK(length(CAST(details_json AS BLOB))<=8192),
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    UNIQUE(job_id,job_version)
);
CREATE INDEX export_job_events_read ON export_job_events(job_id,event_id);

CREATE TRIGGER export_jobs_insert_guard BEFORE INSERT ON export_jobs
WHEN NEW.state<>'queued' OR NEW.phase<>'accepted' OR NEW.row_version<>1
 OR NEW.claim_version<>0 OR NEW.owner_id IS NOT NULL
 OR NEW.started_at IS NOT NULL OR NEW.finished_at IS NOT NULL
 OR NEW.recovery_attempts<>0 OR NEW.recovery_first_at IS NOT NULL
 OR NEW.seq IS NOT (SELECT COALESCE(MAX(seq),0)+1 FROM export_jobs)
BEGIN SELECT RAISE(ABORT,'export_job_initial_state_invalid'); END;

CREATE TRIGGER export_jobs_identity_immutable
BEFORE UPDATE ON export_jobs
WHEN NEW.job_id IS NOT OLD.job_id OR NEW.seq IS NOT OLD.seq
 OR NEW.schema_version IS NOT OLD.schema_version
 OR NEW.kind IS NOT OLD.kind OR NEW.domain IS NOT OLD.domain
 OR NEW.subject_kind IS NOT OLD.subject_kind OR NEW.subject_id IS NOT OLD.subject_id
 OR NEW.portal IS NOT OLD.portal OR NEW.action IS NOT OLD.action
 OR NEW.source IS NOT OLD.source OR NEW.actor_ref IS NOT OLD.actor_ref
 OR NEW.idempotency_key IS NOT OLD.idempotency_key
 OR NEW.request_json IS NOT OLD.request_json OR NEW.request_sha256 IS NOT OLD.request_sha256
 OR NEW.batch_id IS NOT OLD.batch_id OR NEW.policy_id IS NOT OLD.policy_id
 OR NEW.policy_version IS NOT OLD.policy_version OR NEW.slot_key IS NOT OLD.slot_key
 OR NEW.package_mode IS NOT OLD.package_mode OR NEW.requested_package_id IS NOT OLD.requested_package_id
 OR NEW.planned_attempt_id IS NOT OLD.planned_attempt_id OR NEW.parent_job_id IS NOT OLD.parent_job_id
 OR NEW.created_at IS NOT OLD.created_at
 OR (OLD.package_id IS NOT NULL AND NEW.package_id IS NOT OLD.package_id)
 OR (OLD.binding_sha256 IS NOT NULL AND NEW.binding_sha256 IS NOT OLD.binding_sha256)
 OR (OLD.attempt_id IS NOT NULL AND NEW.attempt_id IS NOT OLD.attempt_id)
 OR (OLD.attempt_anchor_id IS NOT NULL AND NEW.attempt_anchor_id IS NOT OLD.attempt_anchor_id)
 OR (OLD.recovery_first_at IS NOT NULL AND NEW.recovery_first_at IS NOT OLD.recovery_first_at)
BEGIN
    SELECT RAISE(ABORT,'export_job_identity_immutable');
END;

CREATE TRIGGER export_jobs_version_guard
BEFORE UPDATE ON export_jobs
WHEN NEW.row_version<>OLD.row_version+1 OR NEW.claim_version<OLD.claim_version
 OR NEW.claim_version>OLD.claim_version+1
 OR NEW.recovery_attempts<OLD.recovery_attempts OR NEW.recovery_attempts>OLD.recovery_attempts+1
BEGIN
    SELECT RAISE(ABORT,'export_job_version_conflict');
END;

CREATE TRIGGER export_jobs_state_guard
BEFORE UPDATE OF state ON export_jobs
WHEN NEW.state<>OLD.state AND NOT (
    (OLD.state='queued' AND NEW.state IN ('running','cancelled'))
 OR (OLD.state='running' AND NEW.state IN ('queued','completed','blocked','failed','needs_review'))
 OR (OLD.state='needs_review' AND NEW.state='completed')
)
BEGIN
    SELECT RAISE(ABORT,'export_job_transition_forbidden');
END;

CREATE TRIGGER export_jobs_terminal_immutable
BEFORE UPDATE ON export_jobs
WHEN OLD.state IN ('completed','blocked','failed','cancelled')
 OR (OLD.state='needs_review' AND NEW.state<>'completed')
BEGIN
    SELECT RAISE(ABORT,'export_job_terminal_immutable');
END;

CREATE TRIGGER export_jobs_no_delete BEFORE DELETE ON export_jobs
BEGIN SELECT RAISE(ABORT,'export_job_retention_requires_contract'); END;

CREATE TRIGGER export_job_events_consistency BEFORE INSERT ON export_job_events
WHEN NOT EXISTS (SELECT 1 FROM export_jobs AS j WHERE j.job_id=NEW.job_id
    AND j.row_version=NEW.job_version AND j.state=NEW.to_state
    AND j.phase=NEW.phase AND j.claim_version=NEW.claim_version)
BEGIN SELECT RAISE(ABORT,'export_job_event_mismatch'); END;
CREATE TRIGGER export_job_events_no_update BEFORE UPDATE ON export_job_events
BEGIN SELECT RAISE(ABORT,'export_job_audit_immutable'); END;
CREATE TRIGGER export_job_events_no_delete BEFORE DELETE ON export_job_events
BEGIN SELECT RAISE(ABORT,'export_job_audit_immutable'); END;
'''

_HEX32 = re.compile(r'^[0-9a-f]{32}$')
_ACTOR = re.compile(r'^(user:[0-9]{1,19}|policy:[a-z0-9][a-z0-9_-]{0,63})$')
_POLICY_ID = re.compile(r'^[a-z0-9][a-z0-9_-]{0,63}$')
_INT64 = 2 ** 63 - 1
TERMINAL = ('completed', 'blocked', 'failed', 'cancelled')
_DOMESTIC_PORTALS = ('no', 'domiporta', 'tabelaofert', 'gruntguru')
_FOREIGN_PORTALS = ('domiporta', 'tabelaofert')
clock = time.time  # tests may replace; seconds since epoch


# ----------------------------------------------------------------- errors
class JobError(Exception):
    code = 'job_error'

    def __init__(self, message=None):
        super().__init__(message or self.code)


def _error(name, code):
    return type(name, (JobError,), {'code': code})


InvalidRequest = _error('InvalidRequest', 'invalid_request')
SchemaUnavailable = _error('SchemaUnavailable', 'schema_unavailable')
SchemaMismatch = _error('SchemaMismatch', 'schema_mismatch')
StorageBusy = _error('StorageBusy', 'storage_busy')
StorageUnavailable = _error('StorageUnavailable', 'storage_unavailable')
StorageLimit = _error('StorageLimit', 'job_storage_limit')
IdempotencyConflict = _error('IdempotencyConflict', 'idempotency_conflict')
ActiveJobConflict = _error('ActiveJobConflict', 'active_job_conflict')
DispatchPaused = _error('DispatchPaused', 'dispatch_paused')
JobNotFound = _error('JobNotFound', 'job_not_found')
JobNotQueued = _error('JobNotQueued', 'job_not_queued')
VersionConflict = _error('VersionConflict', 'job_version_conflict')
ClaimLost = _error('ClaimLost', 'claim_lost')
AutomationNotSupported = _error('AutomationNotSupported', 'automation_not_supported')
ManualFirstRequired = _error('ManualFirstRequired', 'manual_first_required')


@dataclass(frozen=True)
class JobReceipt:
    job_id: str
    kind: str
    state: str
    phase: str
    row_version: int
    replayed: bool


@dataclass(frozen=True)
class JobClaim:
    job_id: str
    seq: int
    owner_id: str
    claim_version: int
    row_version: int
    kind: str
    state: str
    phase: str
    domain: str
    subject_kind: str
    subject_id: int
    portal: str
    action: str
    source: str
    actor_ref: str
    package_mode: str
    requested_package_id: object
    package_id: object
    planned_attempt_id: object
    attempt_id: object
    binding_sha256: object
    attempt_anchor_id: object
    observed_attempt_event_id: object
    parent_job_id: object
    recovery_attempts: int
    recovery_first_at: object
    started_at: object
    request: dict


# ------------------------------------------------------------- connection
def now_iso(epoch=None):
    value = clock() if epoch is None else epoch
    moment = datetime.fromtimestamp(value, timezone.utc)
    return moment.strftime('%Y-%m-%dT%H:%M:%S.') + '%03dZ' % (moment.microsecond // 1000)


def parse_iso(value):
    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone.utc).timestamp()


def db_path():
    return storage_paths.idb_db_path()


def _map(exc):
    text = str(exc).lower()
    if isinstance(exc, sqlite3.OperationalError):
        if 'locked' in text or 'busy' in text:
            return StorageBusy('storage_busy')
        if 'no such table' in text and 'export_job' in text:
            return SchemaUnavailable('schema_unavailable')
    return StorageUnavailable('storage_unavailable')


def _connect(timeout):
    path = db_path()
    if not path.is_file():
        raise SchemaUnavailable('database_missing')
    try:
        conn = sqlite3.connect(path.resolve().as_uri() + '?mode=rw', uri=True, timeout=timeout,
                               isolation_level=None)
        conn.row_factory = sqlite3.Row
        conn.execute('PRAGMA foreign_keys=ON')
        conn.execute('PRAGMA synchronous=FULL')
        return conn
    except sqlite3.Error as exc:
        raise _map(exc) from exc


@contextmanager
def _transaction(timeout):
    conn = _connect(timeout)
    try:
        try:
            conn.execute('BEGIN IMMEDIATE')
            yield conn
            conn.execute('COMMIT')
        except sqlite3.Error as exc:
            _rollback(conn)
            raise _map(exc) from exc
        except BaseException:
            _rollback(conn)
            raise
    finally:
        conn.close()


@contextmanager
def _reader(timeout):
    conn = _connect(timeout)
    try:
        try:
            yield conn
        except sqlite3.Error as exc:
            raise _map(exc) from exc
    finally:
        conn.close()


def _rollback(conn):
    try:
        conn.execute('ROLLBACK')
    except sqlite3.Error:
        pass


# ----------------------------------------------------------------- schema
def statements():
    result, current = [], ''
    for line in DDL.strip().splitlines():
        current += line + '\n'
        if sqlite3.complete_statement(current):
            result.append(current.strip())
            current = ''
    assert not current.strip()
    return result


def _normalise(sql):
    return re.sub(r'\s+', ' ', sql or '').strip()


def _reference():
    with closing(sqlite3.connect(':memory:')) as conn:
        for statement in statements():
            conn.execute(statement)
        return {name: _normalise(sql) for name, sql in conn.execute(
            "SELECT name,sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'")}


def schema_state(conn):
    """'absent' (no own objects), 'ready' (exact), or 'mismatch'."""
    expected = _reference()
    actual = {row[0]: _normalise(row[1]) for row in conn.execute(
        'SELECT name,sql FROM sqlite_master WHERE sql IS NOT NULL')
        if row[0] in expected or row[0].startswith(('export_job', 'sqlite_autoindex_export_job'))}
    if not actual:
        return 'absent'
    return 'ready' if actual == expected else 'mismatch'


_migration_hook = None  # test seam: called with the statement index before each statement


def init_schema(*, backup=True):
    """Explicit migration. Never called at import. Returns created|already_current."""
    from InvestmentManager import scheduler_state
    from .input_consistency import input_lock
    path = db_path()
    if not path.is_file():
        raise SchemaUnavailable('database_missing')
    with scheduler_state.runner_lock() as acquired:
        if not acquired:
            raise StorageBusy('runner_busy')
        with input_lock():
            conn = sqlite3.connect(path.resolve().as_uri() + '?mode=rw', uri=True, timeout=WORKER_TIMEOUT,
                                   isolation_level=None)
            try:
                state = schema_state(conn)
                if state == 'ready':
                    return 'already_current'
                if state == 'mismatch':
                    raise SchemaMismatch('schema_mismatch')
                if backup:
                    folder = path.parent / 'backups'
                    folder.mkdir(parents=True, exist_ok=True)
                    stamp = datetime.fromtimestamp(clock(), timezone.utc).strftime('%Y%m%d_%H%M%S_%f')
                    with closing(sqlite3.connect(folder / ('IDB_%s_pre_export_jobs.db' % stamp))) as target:
                        conn.backup(target)
                conn.execute('BEGIN IMMEDIATE')
                try:
                    for index, statement in enumerate(statements()):
                        if _migration_hook:
                            _migration_hook(index)
                        conn.execute(statement)
                    if _migration_hook:
                        _migration_hook(len(statements()))
                    if schema_state(conn) != 'ready':
                        raise SchemaMismatch('schema_mismatch')
                    conn.execute('COMMIT')
                except BaseException:
                    _rollback(conn)
                    raise
                return 'created'
            except sqlite3.Error as exc:
                raise _map(exc) from exc
            finally:
                conn.close()


def verify_schema():
    with _reader(WORKER_TIMEOUT) as conn:
        return schema_state(conn)


# ---------------------------------------------------------------- storage
def _storage_sizes(path):
    with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=0)) as conn:
        pages = conn.execute('PRAGMA page_count').fetchone()[0]
        size = conn.execute('PRAGMA page_size').fetchone()[0]
        free = conn.execute('PRAGMA freelist_count').fetchone()[0]
    physical = max(path.stat().st_size, pages * size)
    return physical, free * size


def storage_report(*, events=False):
    path = db_path()
    if not path.is_file():
        raise SchemaUnavailable('database_missing')
    try:
        physical, free = _storage_sizes(path)
    except (sqlite3.Error, OSError) as exc:
        raise StorageUnavailable('storage_unavailable') from exc
    report = {'physical_bytes': physical, 'free_bytes': free, 'used_bytes': physical - free,
              'warn': physical > WARN_BYTES, 'blocked': physical >= BLOCK_BYTES,
              'warn_bytes': WARN_BYTES, 'block_bytes': BLOCK_BYTES}
    if events:
        report['events'] = _event_counts(path)
    return report


def _event_counts(idb):
    result = {}
    sources = [('domestic_attempt_events', idb, 'offer_portal_sync_events'),
               ('export_job_events', idb, 'export_job_events'),
               ('foreign_attempt_events', storage_paths.foreign_offers_db_path(), 'foreign_offer_portal_sync_events')]
    for key, path, table in sources:
        count = None
        if path.is_file():
            try:
                with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=0)) as conn:
                    if conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone():
                        count = conn.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0]
            except sqlite3.Error:
                count = None
        entry = {'count': count}
        if key != 'export_job_events':
            entry.update(max=MAX_EVENTS, ratio=None if count is None else count / MAX_EVENTS,
                         warn=bool(count is not None and count / MAX_EVENTS >= 0.8))
        result[key] = entry
    return result


def verify_integrity(conn=None):
    """Job ids whose events do not match row_version (count and max version)."""
    query = '''SELECT j.job_id FROM export_jobs j WHERE j.row_version <>
        (SELECT COUNT(*) FROM export_job_events e WHERE e.job_id=j.job_id)
        OR j.row_version <> COALESCE((SELECT MAX(job_version) FROM export_job_events e WHERE e.job_id=j.job_id),0)'''
    if conn is not None:
        return [row[0] for row in conn.execute(query)]
    with _reader(WORKER_TIMEOUT) as own:
        return [row[0] for row in own.execute(query)]


# -------------------------------------------------------------- validation
def _ident(value, name):
    if type(value) is not int or not 0 < value <= _INT64:
        raise InvalidRequest('invalid_' + name)
    return value


def _hex32(value, name):
    if not isinstance(value, str) or not _HEX32.fullmatch(value):
        raise InvalidRequest('invalid_' + name)
    return value


def _actor(value):
    if not isinstance(value, str) or not _ACTOR.fullmatch(value):
        raise InvalidRequest('invalid_actor')
    return value


def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)


def _intent(intent):
    if not isinstance(intent, dict) or set(intent) != {'domain', 'subject', 'portal', 'action', 'package'}:
        raise InvalidRequest('invalid_request')
    subject, package = intent['subject'], intent['package']
    if not isinstance(subject, dict) or set(subject) != {'kind', 'id'}:
        raise InvalidRequest('invalid_subject')
    if not isinstance(package, dict) or 'mode' not in package or set(package) - {'mode', 'package_id'}:
        raise InvalidRequest('invalid_package')
    domain, kind, portal, action = intent['domain'], subject['kind'], intent['portal'], intent['action']
    _ident(subject['id'], 'subject')
    ok = ((domain == 'domestic' and kind == 'offer' and portal in _DOMESTIC_PORTALS)
          or (domain == 'foreign' and kind == 'foreign_offer' and portal in _FOREIGN_PORTALS)
          or (domain == 'foreign' and kind == 'cyprus_development' and portal == 'tabelaofert' and action == 'add'))
    if not ok or action not in ('add', 'delete'):
        raise InvalidRequest('invalid_combination')
    mode = package['mode']
    if mode == 'existing':
        if set(package) != {'mode', 'package_id'}:
            raise InvalidRequest('invalid_package')
        _hex32(package['package_id'], 'package')
    elif mode == 'ensure_current':
        if set(package) != {'mode'}:
            raise InvalidRequest('invalid_package')
    else:
        raise InvalidRequest('invalid_package')
    return {'domain': domain, 'subject': {'kind': kind, 'id': subject['id']}, 'portal': portal,
            'action': action, 'package': dict(package)}


def _admission():
    report = storage_report()
    if report['blocked']:
        raise StorageLimit('job_storage_limit')


def _lookup(conn, actor, key, source='manual'):
    return conn.execute('SELECT * FROM export_jobs WHERE actor_ref=? AND source=? AND idempotency_key=?',
                        (actor, source, key)).fetchone()


def _receipt(row, replayed):
    return JobReceipt(row['job_id'], row['kind'], row['state'], row['phase'], row['row_version'], replayed)


def _details(details):
    text = canonical(details or {})
    if len(text.encode('utf-8')) > 8000:
        text = canonical({'truncated': True})
    return text


def _event(conn, job_id, event_type, actor, *, from_state=None, reason_code=None, details=None):
    row = conn.execute('SELECT row_version,state,phase,claim_version FROM export_jobs WHERE job_id=?',
                       (job_id,)).fetchone()
    conn.execute('''INSERT INTO export_job_events(job_id,job_version,event_type,actor_ref,claim_version,
        from_state,to_state,phase,reason_code,details_json) VALUES (?,?,?,?,?,?,?,?,?,?)''',
                 (job_id, row['row_version'], event_type, actor, row['claim_version'], from_state,
                  row['state'], row['phase'], reason_code, _details(details)))


def _insert(conn, values, actor, canon, replay_key, source='manual', details=None):
    """Insert job + accepted event. Caller holds BEGIN IMMEDIATE."""
    values = dict(values, state='queued', phase='accepted', source=source, actor_ref=actor,
                  request_json=canon, request_sha256=hashlib.sha256(canon.encode('utf-8')).hexdigest(),
                  idempotency_key=replay_key)
    columns = ','.join(values)
    marks = ','.join('?' * len(values))
    try:
        conn.execute(f'INSERT INTO export_jobs(seq,{columns}) VALUES '
                     f'((SELECT COALESCE(MAX(seq),0)+1 FROM export_jobs),{marks})', list(values.values()))
    except sqlite3.IntegrityError as exc:
        text = str(exc)
        if ('export_jobs.domain, export_jobs.subject_kind' in text or 'export_jobs.domain, export_jobs.attempt_id' in text
                or 'export_jobs.policy_id' in text):
            raise ActiveJobConflict('active_job_conflict') from exc
        raise
    _event(conn, values['job_id'], 'accepted', actor, details=details)
    return conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (values['job_id'],)).fetchone()


def _manual_first_gate(intent):
    """Hard backend rule (Q-D09-4): while the unit's newest attempt is closed by a D09 'not_published' decision and
    no manual delivery job was created after it, automation may not create a job (cooldown/restart irrelevant:
    the proof is durable in the attempt history and the job store). Fails closed when the history is unreadable."""
    from . import export_attempts as attempts
    found = attempts.unit_attempts_ro(intent['subject'], intent['portal'], domain=intent['domain'])
    if found['state'] != 'ok':
        raise StorageUnavailable('storage_unavailable')
    latest = found['items'][0] if found['items'] else None
    if latest is None or latest['state'] != 'resolved_not_published':
        return
    since = (latest.get('resolution') or {}).get('decided_at')
    subject = intent['subject']
    if not since or not manual_delivery_since(intent['domain'], subject['kind'], subject['id'], intent['portal'], since):
        raise ManualFirstRequired('manual_first_required')


def manual_delivery_since(domain, subject_kind, subject_id, portal, since_iso):
    """Is there a manual delivery job for the unit created after `since_iso` that was not cancelled?"""
    with _reader(WORKER_TIMEOUT) as conn:
        return conn.execute("SELECT 1 FROM export_jobs WHERE kind='delivery' AND source='manual' AND domain=? AND subject_kind=? "
                            "AND subject_id=? AND portal=? AND state<>'cancelled' AND created_at>? LIMIT 1",
                            (domain, subject_kind, subject_id, portal, since_iso)).fetchone() is not None


def _policy(policy, actor):
    """Validate the automation policy reference; the actor must be exactly policy:<id>."""
    if (not isinstance(policy, dict) or set(policy) != {'id', 'version', 'slot'} or not isinstance(policy['id'], str)
            or not _POLICY_ID.fullmatch(policy['id']) or type(policy['version']) is not int or policy['version'] < 1
            or not isinstance(policy['slot'], str) or not 1 <= len(policy['slot']) <= 64 or actor != 'policy:' + policy['id']):
        raise InvalidRequest('invalid_policy')
    return policy


def create_delivery(intent, *, actor, idempotency_key, dispatch_enabled=None, source='manual', policy=None):
    """Persist a delivery intent. 'replayed' receipts skip dispatch/limit checks.

    source='automation' is reserved for export_automation: it needs an explicit policy reference and a
    policy:<id> actor; HTTP never passes either. A manual job never carries a policy actor.
    """
    if source not in ('manual', 'automation') or (source == 'automation') != (policy is not None):
        raise AutomationNotSupported('automation_not_supported')
    actor = _actor(actor)
    if source == 'manual' and not actor.startswith('user:'):
        raise InvalidRequest('invalid_actor')
    _hex32(idempotency_key, 'idempotency_key')
    intent = _intent(intent)
    canon = canonical(intent)
    extra, details = {}, None
    if source == 'automation':
        _manual_first_gate(intent)                   # D09: after 'not published' the first new job must be manual
        policy = _policy(policy, actor)
        extra = dict(policy_id=policy['id'], policy_version=policy['version'], slot_key=policy['slot'])
        details = {'automation': {'policy_id': policy['id'], 'policy_version': policy['version'], 'slot': policy['slot']}}
    with _transaction(HTTP_TIMEOUT) as conn:
        existing = _lookup(conn, actor, idempotency_key, source)
        if existing is not None:
            if existing['request_json'] != canon:
                raise IdempotencyConflict('idempotency_conflict')
            return _receipt(existing, True)
        if dispatch_enabled is not True:
            raise DispatchPaused('dispatch_paused')
        _admission()
        package = intent['package']
        values = dict(job_id=uuid.uuid4().hex, kind='delivery', domain=intent['domain'],
                      subject_kind=intent['subject']['kind'], subject_id=intent['subject']['id'],
                      portal=intent['portal'], action=intent['action'], package_mode=package['mode'],
                      requested_package_id=package.get('package_id'), planned_attempt_id=uuid.uuid4().hex, **extra)
        return _receipt(_insert(conn, values, actor, canon, idempotency_key, source, details), False)


def create_ack_recovery(target, *, actor, idempotency_key, parent_job_id=None):
    """ACK-only intent for an existing attempt. Never blocked by storage limit or pause."""
    actor = _actor(actor)
    if not actor.startswith('user:'):                  # ACK-only is an operator action, never an automation one
        raise InvalidRequest('invalid_actor')
    _hex32(idempotency_key, 'idempotency_key')
    need = {'domain', 'attempt_id', 'subject_kind', 'subject_id', 'portal', 'action', 'package_id',
            'binding_sha256', 'attempt_anchor_id'}
    if not isinstance(target, dict) or set(target) != need:
        raise InvalidRequest('invalid_request')
    _hex32(target['attempt_id'], 'attempt')
    _hex32(target['package_id'], 'package')
    if not isinstance(target['binding_sha256'], str) or not re.fullmatch(r'[0-9a-f]{64}', target['binding_sha256']):
        raise InvalidRequest('invalid_binding')
    _ident(target['subject_id'], 'subject')
    _ident(target['attempt_anchor_id'], 'anchor')
    if parent_job_id is not None:
        _hex32(parent_job_id, 'parent')
    canon = canonical({'kind': 'ack_only', 'domain': target['domain'], 'attempt_id': target['attempt_id']})
    with _transaction(HTTP_TIMEOUT) as conn:
        existing = _lookup(conn, actor, idempotency_key)
        if existing is not None:
            if existing['request_json'] != canon:
                raise IdempotencyConflict('idempotency_conflict')
            return _receipt(existing, True)
        values = dict(job_id=uuid.uuid4().hex, kind='ack_only', domain=target['domain'],
                      subject_kind=target['subject_kind'], subject_id=target['subject_id'],
                      portal=target['portal'], action=target['action'], package_mode='none',
                      package_id=target['package_id'], attempt_id=target['attempt_id'],
                      binding_sha256=target['binding_sha256'], attempt_anchor_id=target['attempt_anchor_id'],
                      parent_job_id=parent_job_id)
        try:
            return _receipt(_insert(conn, values, actor, canon, idempotency_key), False)
        except sqlite3.IntegrityError as exc:
            raise InvalidRequest('invalid_combination') from exc


# ------------------------------------------------------------------ reads
def _metrics(value):
    try:
        return json.loads(value)
    except (TypeError, ValueError):
        return {}


def _view(row):
    return {'job_id': row['job_id'], 'kind': row['kind'], 'domain': row['domain'],
            'subject': {'kind': row['subject_kind'], 'id': row['subject_id']},
            'portal': row['portal'], 'action': row['action'], 'source': row['source'],
            'actor_ref': row['actor_ref'], 'state': row['state'], 'phase': row['phase'],
            'reason_code': row['reason_code'], 'row_version': row['row_version'],
            'created_at': row['created_at'], 'updated_at': row['updated_at'],
            'started_at': row['started_at'], 'finished_at': row['finished_at'],
            'package_id': row['package_id'], 'attempt_id': row['attempt_id'],
            'parent_job_id': row['parent_job_id'], 'batch_id': row['batch_id'],
            'metrics': _metrics(row['metrics_json'])}


def _short(row):
    return {key: row[key] for key in ('job_id', 'kind', 'domain', 'portal', 'action', 'state', 'phase',
                                      'reason_code', 'row_version', 'created_at', 'finished_at')} | {
        'subject': {'kind': row['subject_kind'], 'id': row['subject_id']}}


def get_job(job_id, *, internal=False):
    _hex32(job_id, 'job_id')
    with _reader(HTTP_TIMEOUT) as conn:
        row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job_id,)).fetchone()
    if row is None:
        raise JobNotFound('job_not_found')
    view = _view(row)
    if internal:
        view['_internal'] = {key: row[key] for key in ('attempt_anchor_id', 'binding_sha256', 'planned_attempt_id',
                                                        'observed_attempt_event_id', 'seq', 'requested_package_id',
                                                        'package_mode')}
    return view


def encode_cursor(seq):
    return base64.urlsafe_b64encode(str(seq).encode()).decode().rstrip('=')


def decode_cursor(value):
    try:
        text = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4)).decode('ascii')
        if not re.fullmatch(r'[1-9][0-9]{0,18}', text):
            raise ValueError
        return int(text)
    except (ValueError, TypeError, UnicodeError):
        raise InvalidRequest('invalid_cursor') from None


def list_jobs(*, limit=50, before=None, state=None, kind=None, domain=None, batch_id=None):
    if type(limit) is not int or not 1 <= limit <= 100:
        raise InvalidRequest('invalid_request')
    where, args = [], []
    for column, value, allowed in (('state', state, ('queued', 'running', 'completed', 'blocked', 'failed', 'needs_review', 'cancelled')),
                                   ('kind', kind, ('delivery', 'ack_only')),
                                   ('domain', domain, ('domestic', 'foreign'))):
        if value is not None:
            if value not in allowed:
                raise InvalidRequest('invalid_request')
            where.append(f'{column}=?')
            args.append(value)
    if batch_id is not None:
        where.append('batch_id=?')
        args.append(_hex32(batch_id, 'batch_id'))
    if before is not None:
        where.append('seq<?')
        args.append(decode_cursor(before))
    sql = 'SELECT * FROM export_jobs' + (' WHERE ' + ' AND '.join(where) if where else '') + ' ORDER BY seq DESC LIMIT ?'
    with _reader(HTTP_TIMEOUT) as conn:
        rows = conn.execute(sql, [*args, limit + 1]).fetchall()
    more = len(rows) > limit
    rows = rows[:limit]
    return {'items': [_short(row) for row in rows],
            'next_cursor': encode_cursor(rows[-1]['seq']) if more and rows else None}


def list_events(job_id, *, after=0, limit=100, max_bytes=None):
    _hex32(job_id, 'job_id')
    if type(after) is not int or after < 0 or after > _INT64 or type(limit) is not int or not 1 <= limit <= 100:
        raise InvalidRequest('invalid_request')
    cap = MAX_EVENT_RESPONSE_BYTES if max_bytes is None else max_bytes
    with _reader(HTTP_TIMEOUT) as conn:
        if conn.execute('SELECT 1 FROM export_jobs WHERE job_id=?', (job_id,)).fetchone() is None:
            raise JobNotFound('job_not_found')
        rows = conn.execute('SELECT * FROM export_job_events WHERE job_id=? AND event_id>? ORDER BY event_id LIMIT ?',
                            (job_id, after, limit + 1)).fetchall()
    items, size, truncated = [], 0, False
    for row in rows[:limit]:
        item = {key: row[key] for key in ('event_id', 'job_version', 'event_type', 'actor_ref', 'claim_version',
                                          'from_state', 'to_state', 'phase', 'reason_code', 'created_at')}
        item['details'] = _metrics(row['details_json'])
        length = len(canonical(item).encode('utf-8'))
        if items and size + length > cap:
            truncated = True
            break
        items.append(item)
        size += length
    more = truncated or len(rows) > limit
    return {'items': items, 'next_after': items[-1]['event_id'] if items else after,
            'truncated': truncated, 'more': more}


# ----------------------------------------------------------------- cancel
def cancel_job(job_id, *, expected_version, actor, attempt_guard=None):
    """Cancel a queued job (CAS on state and row_version). Repeat on cancelled: no new event.

    attempt_guard(view) is called under input_lock before the CAS and must raise
    JobNotQueued when the linked attempt is no longer safely cancellable.
    """
    from .input_consistency import input_lock, ConsistencyError
    _hex32(job_id, 'job_id')
    actor = _actor(actor)
    try:
        lock = input_lock()
        lock.__enter__()
    except ConsistencyError as exc:
        raise StorageBusy('storage_busy') from exc
    try:
        with _transaction(HTTP_TIMEOUT) as conn:
            row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job_id,)).fetchone()
            if row is None:
                raise JobNotFound('job_not_found')
            if row['state'] == 'cancelled':
                return _view(row)
            if type(expected_version) is not int or row['row_version'] != expected_version:
                raise VersionConflict('job_version_conflict')
            if row['state'] != 'queued':
                raise JobNotQueued('job_not_queued')
            if attempt_guard is not None:
                attempt_guard(_view(row))
            changed = conn.execute('''UPDATE export_jobs SET state='cancelled',phase='finished',
                row_version=row_version+1,finished_at=?,reason_code='cancelled_by_actor',
                updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')
                WHERE job_id=? AND state='queued' AND row_version=?''',
                                   (now_iso(), job_id, expected_version)).rowcount
            if changed != 1:
                raise VersionConflict('job_version_conflict')
            _event(conn, job_id, 'cancelled', actor, from_state='queued', reason_code='cancelled_by_actor')
            return _view(conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job_id,)).fetchone())
    finally:
        lock.__exit__(None, None, None)


# ----------------------------------------------------------------- worker
def _claim(row, request=None):
    return JobClaim(job_id=row['job_id'], seq=row['seq'], owner_id=row['owner_id'], claim_version=row['claim_version'],
                    row_version=row['row_version'], kind=row['kind'], state=row['state'], phase=row['phase'],
                    domain=row['domain'], subject_kind=row['subject_kind'], subject_id=row['subject_id'],
                    portal=row['portal'], action=row['action'], source=row['source'], actor_ref=row['actor_ref'],
                    package_mode=row['package_mode'], requested_package_id=row['requested_package_id'],
                    package_id=row['package_id'], planned_attempt_id=row['planned_attempt_id'],
                    attempt_id=row['attempt_id'], binding_sha256=row['binding_sha256'],
                    attempt_anchor_id=row['attempt_anchor_id'], observed_attempt_event_id=row['observed_attempt_event_id'],
                    parent_job_id=row['parent_job_id'], recovery_attempts=row['recovery_attempts'],
                    recovery_first_at=row['recovery_first_at'], started_at=row['started_at'],
                    request=json.loads(row['request_json']))


WORKER = 'system:runner'


def claim_next(kind, *, owner_id=None, exclude_domains=(), timeout=WORKER_TIMEOUT):
    """Claim the queued job with the lowest seq (CAS). None when nothing is eligible."""
    owner_id = owner_id or uuid.uuid4().hex
    if kind not in ('delivery', 'ack_only'):
        raise InvalidRequest('invalid_kind')
    with _transaction(timeout) as conn:
        marks = ','.join('?' * len(exclude_domains))
        extra = f' AND domain NOT IN ({marks})' if exclude_domains else ''
        row = conn.execute(f"SELECT * FROM export_jobs WHERE kind=? AND state='queued'{extra} ORDER BY seq LIMIT 1",
                           (kind, *exclude_domains)).fetchone()
        if row is None:
            return None
        changed = conn.execute('''UPDATE export_jobs SET state='running',owner_id=?,claim_version=claim_version+1,
            row_version=row_version+1,phase='claimed',started_at=COALESCE(started_at,?),
            updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')
            WHERE job_id=? AND state='queued' AND row_version=?''',
                               (owner_id, now_iso(), row['job_id'], row['row_version'])).rowcount
        if changed != 1:
            return None
        _event(conn, row['job_id'], 'claimed', WORKER, from_state='queued')
        return _claim(conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (row['job_id'],)).fetchone())


def orphans(limit=5, *, timeout=WORKER_TIMEOUT):
    """Running jobs ordered by seq. Valid only for a caller holding the runner lock."""
    with _reader(timeout) as conn:
        return [_claim(row) for row in conn.execute(
            "SELECT * FROM export_jobs WHERE state='running' ORDER BY seq LIMIT ?", (limit,))]


def queued_count(*, timeout=WORKER_TIMEOUT):
    with _reader(timeout) as conn:
        return conn.execute("SELECT COUNT(*) FROM export_jobs WHERE state='queued'").fetchone()[0]


def _refence(job, owner_id, *, event_type, phase, reason_code, details, recovery, timeout):
    with _transaction(timeout) as conn:
        row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job.job_id,)).fetchone()
        if row is None or row['state'] != 'running' or row['claim_version'] != job.claim_version:
            raise ClaimLost('claim_lost')
        first = row['recovery_first_at'] or (now_iso() if recovery else None)
        attempts = row['recovery_attempts'] + (1 if recovery else 0)
        conn.execute('''UPDATE export_jobs SET owner_id=?,claim_version=claim_version+1,row_version=row_version+1,
            phase=?,recovery_attempts=?,recovery_first_at=?,updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')
            WHERE job_id=? AND state='running' AND claim_version=?''',
                     (owner_id, phase, attempts, first, job.job_id, job.claim_version))
        _event(conn, job.job_id, event_type, WORKER, from_state='running', reason_code=reason_code, details=details)
        return _claim(conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job.job_id,)).fetchone())


def adopt(job, owner_id=None, *, details=None, timeout=WORKER_TIMEOUT):
    """Take over an orphan (caller holds runner_lock): new owner, claim_version+1, phase recovery."""
    return _refence(job, owner_id or uuid.uuid4().hex, event_type='recovered', phase='recovery',
                    reason_code=None, details=details, recovery=False, timeout=timeout)


def defer_recovery(job, code, owner_id=None, *, timeout=WORKER_TIMEOUT):
    """Count an unresolved recovery read; job stays running with a fresh fence."""
    return _refence(job, owner_id or uuid.uuid4().hex, event_type='recovery_deferred', phase='recovery',
                    reason_code=code, details={'attempt': job.recovery_attempts + 1}, recovery=True,
                    timeout=timeout)


_REFERENCES = ('package_id', 'binding_sha256', 'attempt_id', 'attempt_anchor_id', 'observed_attempt_event_id')
_PHASES = ('accepted', 'claimed', 'qualification', 'preparation', 'snapshot', 'create_requested', 'attempt_linked',
           'start_requested', 'transport', 'result_recorded', 'ack_requested', 'recovery', 'waiting_resource',
           'paused', 'finished')


def _merge_metrics(old, new):
    merged = dict(_metrics(old))
    merged.update(new or {})
    text = canonical(merged)
    if len(text.encode('utf-8')) > 60000:
        return canonical({'incomplete': True}), True
    return text, False


def advance(claim, *, state='running', phase=None, reason_code=None, event_type=None, details=None,
            references=None, metrics=None, timeout=WORKER_TIMEOUT):
    """Owner-fenced coordination step. Returns the updated JobClaim (None when terminal/requeued)."""
    if state not in ('running', 'queued', 'completed', 'blocked', 'failed', 'needs_review'):
        raise InvalidRequest('invalid_state')
    references = references or {}
    if set(references) - set(_REFERENCES):
        raise InvalidRequest('invalid_reference')
    with _transaction(timeout) as conn:
        row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (claim.job_id,)).fetchone()
        if (row is None or row['state'] != 'running' or row['owner_id'] != claim.owner_id
                or row['claim_version'] != claim.claim_version):
            raise ClaimLost('claim_lost')
        new_phase = 'finished' if state in ('completed', 'blocked', 'failed', 'needs_review') else (phase or row['phase'])
        if new_phase not in _PHASES:
            raise InvalidRequest('invalid_phase')
        values = {'state': state, 'phase': new_phase, 'reason_code': reason_code}
        for key, value in references.items():
            old = row[key]
            if key == 'observed_attempt_event_id':
                if type(value) is not int or value <= 0 or (old is not None and value < old):
                    raise InvalidRequest('invalid_reference')
            elif old is not None and old != value:
                raise InvalidRequest('reference_immutable')
            values[key] = value
        metrics_text, incomplete = _merge_metrics(row['metrics_json'], metrics)
        values['metrics_json'] = metrics_text
        if state == 'queued':
            values.update(owner_id=None, claim_version=row['claim_version'] + 1)
        elif state != 'running':
            values.update(owner_id=None, finished_at=now_iso())
        sets = ','.join(f'{key}=?' for key in values)
        conn.execute(f"UPDATE export_jobs SET {sets},row_version=row_version+1,"
                     "updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE job_id=?",
                     [*values.values(), claim.job_id])
        if event_type is None:
            if state != 'running' and state != 'queued':
                event_type = state
            elif state == 'queued':
                event_type = {'waiting_resource': 'resource_wait', 'paused': 'dispatch_paused'}.get(new_phase, 'phase_changed')
            elif 'attempt_id' in references:
                event_type = 'attempt_linked'
            else:
                event_type = 'phase_changed'
        info = dict(details or {})
        if incomplete:
            info['metrics_incomplete'] = True
        _event(conn, claim.job_id, event_type, WORKER, from_state='running', reason_code=reason_code, details=info)
        fresh = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (claim.job_id,)).fetchone()
    return _claim(fresh) if state == 'running' else None


def complete_review(job_id, *, reason_code, details=None, timeout=WORKER_TIMEOUT, actor=None):
    """needs_review -> completed (parent delivery whose own attempt later reached ack_completed)."""
    with _transaction(timeout) as conn:
        row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (job_id,)).fetchone()
        if row is None:
            raise JobNotFound('job_not_found')
        if row['state'] != 'needs_review':
            raise JobNotQueued('job_not_review')
        conn.execute("UPDATE export_jobs SET state='completed',reason_code=?,row_version=row_version+1,"
                     "updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE job_id=?", (reason_code, job_id))
        _event(conn, job_id, 'recovered', actor or WORKER, from_state='needs_review', reason_code=reason_code, details=details)


def open_jobs_for_attempt(attempt_id, conn=None):
    """[(job_id, kind, state)] of queued/running jobs bound to the attempt (planned or linked). conn: caller's IDB.db connection."""
    query = ("SELECT job_id,kind,state FROM export_jobs WHERE state IN ('queued','running') "
             "AND (attempt_id=? OR planned_attempt_id=?)")
    if conn is not None:
        if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='export_jobs'").fetchone():
            return []
        return [tuple(r) for r in conn.execute(query, (attempt_id, attempt_id))]
    try:
        with _reader(WORKER_TIMEOUT) as own:
            return [tuple(r) for r in own.execute(query, (attempt_id, attempt_id))]
    except SchemaUnavailable:
        return []


def needs_review_for_attempt(domain, attempt_id, conn=None):
    """[(job_id, kind)] of needs_review jobs (delivery and ack_only) bound to the attempt."""
    query = ("SELECT job_id,kind FROM export_jobs WHERE state='needs_review' AND domain=? "
             "AND (attempt_id=? OR planned_attempt_id=?) ORDER BY seq")
    if conn is not None:
        return [tuple(r) for r in conn.execute(query, (domain, attempt_id, attempt_id))]
    with _reader(WORKER_TIMEOUT) as own:
        return [tuple(r) for r in own.execute(query, (domain, attempt_id, attempt_id))]


def review_since(job_id, conn=None):
    """Timestamp of the newest event that moved the job to needs_review (executor already stopped by then)."""
    query = "SELECT created_at FROM export_job_events WHERE job_id=? AND to_state='needs_review' ORDER BY event_id DESC LIMIT 1"
    if conn is not None:
        row = conn.execute(query, (job_id,)).fetchone()
    else:
        with _reader(WORKER_TIMEOUT) as own:
            row = own.execute(query, (job_id,)).fetchone()
    return row[0] if row else None


def needs_review_jobs(limit=50):
    """needs_review jobs that have an attempt: [(job_id, kind, domain, attempt_id, anchor_id, portal, reason_code)]."""
    with _reader(WORKER_TIMEOUT) as conn:
        return [tuple(r) for r in conn.execute(
            "SELECT job_id,kind,domain,COALESCE(attempt_id,planned_attempt_id),attempt_anchor_id,portal,reason_code FROM export_jobs "
            "WHERE state='needs_review' AND COALESCE(attempt_id,planned_attempt_id) IS NOT NULL ORDER BY seq LIMIT ?", (limit,))]


def observe(claim, event_type, *, details=None, reason_code=None, timeout=WORKER_TIMEOUT):
    """Observation event without state change (e.g. result_unsaved); bumps row_version."""
    if event_type not in ('result_unsaved', 'metrics_incomplete', 'phase_changed'):
        raise InvalidRequest('invalid_event')
    with _transaction(timeout) as conn:
        row = conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (claim.job_id,)).fetchone()
        if (row is None or row['state'] != 'running' or row['owner_id'] != claim.owner_id
                or row['claim_version'] != claim.claim_version):
            raise ClaimLost('claim_lost')
        conn.execute("UPDATE export_jobs SET row_version=row_version+1,updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') "
                     "WHERE job_id=?", (claim.job_id,))
        _event(conn, claim.job_id, event_type, WORKER, from_state='running', reason_code=reason_code, details=details)
        return _claim(conn.execute('SELECT * FROM export_jobs WHERE job_id=?', (claim.job_id,)).fetchone())


def binding_digest(binding):
    """sha256 of the canonical full binding; stored on the job before CREATE."""
    return hashlib.sha256(canonical(binding).encode('utf-8')).hexdigest()


def check_fence(claim, conn=None):
    """None when `claim` is still the running owner; otherwise a safe reason code.

    Pass the domestic transaction connection (same IDB.db) to read under the caller's
    transaction; foreign callers pass None and get a short read-only connection.
    """
    query = 'SELECT state,owner_id,claim_version FROM export_jobs WHERE job_id=?'
    if conn is None:
        with _reader(WORKER_TIMEOUT) as own:
            row = own.execute(query, (claim.job_id,)).fetchone()
    else:
        row = conn.execute(query, (claim.job_id,)).fetchone()
    if row is None:
        return 'job_missing'
    if row[0] != 'running' or row[1] != claim.owner_id or row[2] != claim.claim_version:
        return 'claim_lost'
    return None


def find_delivery_by_attempt(domain, attempt_id, conn=None):
    """Newest delivery job linked to the attempt: (job_id, state) or None. conn: caller's IDB.db connection."""
    _hex32(attempt_id, 'attempt')
    query = ("SELECT job_id,state FROM export_jobs WHERE kind='delivery' AND domain=? AND attempt_id=? "
             "ORDER BY seq DESC LIMIT 1")
    if conn is not None:
        if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='export_jobs'").fetchone():
            return None
        row = conn.execute(query, (domain, attempt_id)).fetchone()
    else:
        with _reader(HTTP_TIMEOUT) as own:
            row = own.execute(query, (domain, attempt_id)).fetchone()
    return (row[0], row[1]) if row else None


def active_deliveries():
    """{(domain, subject_kind, subject_id, portal): {'job_id', 'state'}} for queued/running/needs_review deliveries."""
    with _reader(HTTP_TIMEOUT) as conn:
        rows = conn.execute("SELECT domain,subject_kind,subject_id,portal,job_id,state FROM export_jobs "
                            "WHERE kind='delivery' AND state IN ('queued','running','needs_review')").fetchall()
    return {(row[0], row[1], row[2], row[3]): {'job_id': row[4], 'state': row[5]} for row in rows}


def automation_snapshot(*, day_since, bad_since):
    """Read-only counters for the automation guard rails (all from the durable job store).

    pending: every non-terminal job (any source); created_day: automation jobs created since day_since;
    cooled: units whose delivery ended blocked/failed since bad_since (any source);
    breaker: automation jobs that ended failed or need review since day_since;
    queued_automation: [(job_id, row_version)] of automation jobs still queued.
    """
    with _reader(WORKER_TIMEOUT) as conn:
        pending = conn.execute("SELECT COUNT(*) FROM export_jobs WHERE state IN ('queued','running','needs_review')").fetchone()[0]
        created = conn.execute("SELECT COUNT(*) FROM export_jobs WHERE source='automation' AND created_at>=?", (day_since,)).fetchone()[0]
        cooled = {(r[0], r[1], r[2], r[3]) for r in conn.execute(
            "SELECT domain,subject_kind,subject_id,portal FROM export_jobs WHERE kind='delivery' "
            "AND state IN ('blocked','failed') AND COALESCE(finished_at,updated_at)>=?", (bad_since,))}
        breaker = conn.execute("SELECT COUNT(*) FROM export_jobs WHERE source='automation' "
                               "AND state IN ('failed','needs_review') AND updated_at>=?", (day_since,)).fetchone()[0]
        queued = [(r[0], r[1]) for r in conn.execute(
            "SELECT job_id,row_version FROM export_jobs WHERE source='automation' AND state='queued' ORDER BY seq LIMIT 200")]
    return {'pending': pending, 'created_day': created, 'cooled': cooled, 'breaker': breaker, 'queued_automation': queued}
