"""Qualified START of a CRM delivery job: fence + dispatch control + job identity + full business qualification.

Orchestration ABOVE the attempt state (export_attempts): it builds the two gates from the job store (export_jobs), the dispatch switch
(export_control) and the queue qualification (sync_tasks) and hands them to export_attempts.start_gated_transport, which runs them inside
its ONE transaction under dictionary lock and input_lock (order: fence, dispatch, identity, _current once, qualification, UNKNOWN, commit).
The three higher modules are imported lazily, exactly as before the move. Server code only; never reachable from HTTP or the legacy RPC.
"""
import re

from . import export_attempts as attempts


def start_qualified_transport(attempt_id,binding,*,job_claim,settings=None,domain='domestic'):
    """START for CRM jobs only: fence + control + identity + _current + full business qualification,
    all in ONE transaction under dictionary lock and input_lock. can_send=True only after commit.
    Server code only; never reachable from HTTP or the legacy RPC.
    """
    if domain not in ('domestic','foreign'): raise attempts.AttemptError('Invalid domain')
    from . import sync_tasks, export_jobs, export_control
    foreign=domain=='foreign'
    root=sync_tasks.source_root()
    def pre(conn,item):
        reason=export_jobs.check_fence(job_claim,None if foreign else conn)
        if reason:return reason
        enabled=export_control.dispatch_enabled()
        if enabled is None:return 'control_unavailable'
        if not enabled:return 'dispatch_paused'
        subject=binding.get('subject') or {'kind':'offer','id':binding['offer_id']}
        if (job_claim.attempt_id!=attempt_id or job_claim.domain!=('foreign' if foreign else 'domestic')
            or (job_claim.subject_kind,job_claim.subject_id)!=(subject['kind'],subject['id'])
            or job_claim.portal!=binding['portal'] or job_claim.action!=binding['action']):
            return 'job_identity_mismatch'
        if job_claim.binding_sha256 is not None and job_claim.binding_sha256!=export_jobs.binding_digest(binding):
            return 'binding_changed'
        return None
    def gate(conn,item):
        unit={'domain':'foreign' if foreign else 'domestic','portal':binding['portal'],'action':binding['action'],
              'subject':binding.get('subject') or {'kind':'offer','id':binding['offer_id']}}
        q=sync_tasks.qualify_unit(conn,root,unit)
        if not q.required:return 'no_longer_required'
        if q.action!=binding['action']:return 'action_changed'
        if foreign and sorted(q.members)!=sorted(binding['members']):return 'membership_changed'
        if q.blocking:return q.blocking[0] if re.fullmatch(r'[a-z0-9_]{1,64}',q.blocking[0]) else 'qualification_blocked'
        return None
    return attempts.start_gated_transport(attempt_id,binding,pre=pre,qualification=gate,settings=settings,domain=domain)
