"""Local foundation for future transport: durable attempts and conditional ACK.

No FTP, SSH, Streamlit or HTTP endpoint. Callers are trusted transport code,
not browser-supplied claims of FTP success. All state uses existing tables.
"""
from contextlib import closing, contextmanager, ExitStack
from contextvars import ContextVar
from functools import wraps
import hashlib
import json
import re
import uuid

from . import domestic_package_catalog as catalog
from . import export_performance as performance
from .input_consistency import ConsistencyError, event as domestic_event, input_lock, input_revision, state_connection as domestic_connection

TYPE = 'export_attempt_v1'
ID = re.compile(r'^[a-f0-9]{32}$')
RESOLUTION_TYPE = 'export_attempt_resolution_v1'      # D09 audit event (both domains; separate tables)
RESOLVABLE = {'transport_unknown', 'ack_rejected'}
RESOLVED_STATES = {'resolved_not_published', 'resolved_superseded', 'resolved_obsolete'}   # closed, no ACK
PACKAGE_CONSUMED = {'ack_completed', 'resolved_not_published'}   # a package used here must not be sent again
OUTCOME_STATE = {'published_exact': 'transport_confirmed', 'not_published': 'resolved_not_published',
                 'superseded': 'resolved_superseded', 'obsolete_after_publish': 'resolved_obsolete'}


_domain = ContextVar('export_attempt_domain', default='domestic')

def _foreign(): return _domain.get() == 'foreign'
def _kind(): return 'export_attempt_v2' if _foreign() else TYPE

def domain_api(function):
    @wraps(function)
    def call(*args, domain='domestic', **kwargs):
        if domain not in ('domestic','foreign'): raise AttemptError('Invalid domain')
        token = _domain.set(domain)
        try: return function(*args, **kwargs)
        finally: _domain.reset(token)
    return call

def event(conn, offer_id, portal, kind, payload):
    if _foreign():
        from .foreign_attempt_inputs import event as foreign_event
        return foreign_event(conn,offer_id,portal,kind,payload)
    return domestic_event(conn,offer_id,portal,kind,payload)

def _revision(conn,offer):
    if _foreign():
        from .foreign_consistency import revision
        return revision(conn)
    return input_revision(conn,offer)

def _same(left,right):
    return (left['portal']==right['portal'] and
            ((left['subject']==right['subject'] or bool(set(left['members']) & set(right['members']))) if _foreign()
             else left['offer_id']==right['offer_id']))


class AttemptError(ConsistencyError):
    pass


@contextmanager
def transaction():
    # Freeze this process's dictionary cache as well. Public remote dictionaries
    # cannot be locked; their existing cache/freshness contract is unchanged.
    from .domestic_dictionaries import _lock as dictionary_lock
    with performance.lock_context(dictionary_lock, 'dictionary_lock'), input_lock():
        if _foreign():
            from .foreign_attempt_inputs import connection
        else: connection=domestic_connection
        with ExitStack() as stack:
            with performance.stage('sqlite_open_schema'):
                conn = stack.enter_context(connection())
            with performance.stage('sqlite_begin.wait'):
                conn.execute('BEGIN IMMEDIATE')
            with performance.stage('sqlite_transaction'):
                yield conn
                with performance.stage('sqlite_commit'):
                    conn.commit()



def _package(package_id, settings, *, allow_retired=False):
    if not isinstance(package_id,str) or not ID.fullmatch(package_id):
        raise AttemptError('Nieprawidłowy identyfikator paczki.')
    if _foreign():
        from .foreign_attempt_inputs import package
        return package(package_id,settings)
    root,base = catalog._root()
    from .domestic_storage import lookup_scope
    with lookup_scope(base):
        _,item,_ = catalog._metadata(base,package_id)
        if item is None:
            raise AttemptError('Nieprawidłowa paczka.')
        diagnostic = catalog.verify_package(package_id,settings=settings,allow_retired=allow_retired)
        if diagnostic['state'] != 'READY':
            raise AttemptError('Paczka nie jest READY: '+diagnostic['state'])
        with catalog._open(catalog.package_folder(base,package_id)/'manifest.json',base) as stream:
            raw = stream.read(catalog.MAX_MANIFEST+1)
        if len(raw)>catalog.MAX_MANIFEST or catalog._manifest(raw,package_id)!=item:
            raise AttemptError('Manifest zmienił się podczas kontroli.')
        return {key:item[key] for key in ('package_id','offer_id','portal','action',
                'input_fingerprint','zip_sha256','zip_size','zip_name')} | {
                    'manifest_sha256':hashlib.sha256(raw).hexdigest()}


def _history(conn,offer_id=None,portal=None):
    table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
    column='foreign_offer_id' if _foreign() else 'offer_id'
    query=f'SELECT id,{column},portal_key,payload_json FROM {table} WHERE event_type=?'
    args=[_kind()]
    if offer_id is not None and portal is None:
        query+=f' AND {column}=?';args.append(offer_id)          # all portals of one anchor (bounded qualification read)
    elif offer_id is not None:
        query+=f' AND {column}=? AND portal_key=?';args.extend((offer_id,portal))
    query+=' ORDER BY id'
    result={}
    for number,offer,key,raw in conn.execute(query,args):
        payload=json.loads(raw)
        if (not isinstance(payload,dict) or not ID.fullmatch(payload.get('attempt_id',''))
            or payload['binding']['offer_id']!=offer or payload['binding']['portal']!=key
            or type(payload.get('prepared_seq')) is not int or payload['prepared_seq']>number):
            raise AttemptError('Niespójna historia prób eksportu.')
        previous=result.get(payload['attempt_id'])
        if previous and any(previous[k]!=payload[k] for k in ('binding','revision','prepared_seq','baseline')):
            raise AttemptError('Tożsamość próby eksportu została zmieniona.')
        payload['event_id']=number
        result[payload['attempt_id']]=payload
    return result


def _find(conn,attempt_id,binding=None):
    if not isinstance(attempt_id,str) or not ID.fullmatch(attempt_id):
        raise AttemptError('Nieprawidłowy identyfikator próby.')
    item=_history(conn).get(attempt_id)
    if item is None or binding is not None and item['binding']!=binding:
        raise AttemptError('Nieznana próba lub niezgodna tożsamość paczki.')
    return item


def _status(conn,binding):
    if _foreign():
        from .foreign_attempt_inputs import status
        return status(conn,binding)
    row=conn.execute('''SELECT is_published,needs_update,last_action,last_filename,
        last_bytes,last_error,last_uploaded_at,updated_at FROM offer_portal_sync
        WHERE offer_id=? AND portal_key=?''',(binding['offer_id'],binding['portal'])).fetchone()
    return list(row) if row is not None else None


def _append(conn,item,state,reason=None):
    payload={k:v for k,v in item.items() if k not in {'event_id','can_send','already_acknowledged','reason'}}
    payload['state']=state
    if reason:payload['reason']=reason
    payload['event_id']=event(conn,item['binding']['offer_id'],item['binding']['portal'],_kind(),payload)
    if state=='transport_unknown':
        event(conn,item['binding']['offer_id'],item['binding']['portal'],
              'export_transport_open_v2' if _foreign() else 'export_transport_open_v1',{'attempt_id':item['attempt_id']})
    elif state in {'ack_completed','transport_failed'}|RESOLVED_STATES:
        event(conn,item['binding']['offer_id'],item['binding']['portal'],
              'export_transport_closed_v2' if _foreign() else 'export_transport_closed_v1',{'attempt_id':item['attempt_id']})
    return payload


def create_attempt(package_id,offer_id=None,portal=None,action=None,*,attempt_id=None,settings=None,subject=None):
    """Register without sending. An unresolved transport prevents a fresh send."""
    if _foreign():
        from .foreign_packages import _selection
        if not isinstance(subject,dict) or set(subject)!={'kind','id'}: raise AttemptError('Invalid subject')
        _selection(subject['kind'],subject['id'],portal,action)
        offer_id=subject['id']
    if (type(offer_id) is not int or offer_id<=0 or not isinstance(portal,str)
        or portal not in catalog.preparation.PORTALS or action not in ('add','delete')):
        raise AttemptError('Nieprawidłowa oferta, portal lub akcja.')
    attempt_id=attempt_id or uuid.uuid4().hex
    if not isinstance(attempt_id,str) or not ID.fullmatch(attempt_id):
        raise AttemptError('Nieprawidłowa próba.')
    with transaction() as conn:
        binding=_package(package_id,settings)
        selected=dict(subject=subject,portal=portal,action=action) if _foreign() else dict(offer_id=offer_id,portal=portal,action=action)
        if any(binding[k]!=v for k,v in selected.items()):
            raise AttemptError('Paczka nie odpowiada wskazanej operacji.')
        revision=_revision(conn,offer_id)
        offer_id=binding['offer_id']
        history=_history(conn)
        if attempt_id in history:
            existing=history[attempt_id]
            if existing['binding']!=binding:raise AttemptError('Próba ma inną tożsamość.')
            return existing
        for item in history.values():
            same=_same(item['binding'],binding)
            if same and item['state'] in {'transport_unknown','transport_confirmed','ack_failed','ack_rejected'}:
                raise AttemptError('Poprzedni transport wymaga uzgodnienia wyniku; nie wolno ponawiać FTP.')
            if item['binding']==binding and item['state']=='ack_completed':
                return item
        if _legacy_pending(conn,offer_id,portal):
            raise AttemptError('Istniejący transport IDBManager wymaga uzgodnienia wyniku; ponowna wysyłka zabroniona.')
        if not _foreign():
            from . import domestic_sets
            _, base = catalog._root()
            domestic_sets.pin(base, package_id)
        payload={'attempt_id':attempt_id,'binding':binding,'revision':revision,
                 'baseline':_status(conn,binding),'prepared_seq':0,'state':'prepared'}
        number=event(conn,offer_id,portal,_kind(),payload)
        payload['prepared_seq']=number
        table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
        conn.execute(f'UPDATE {table} SET payload_json=? WHERE id=?',
                     (json.dumps(payload,ensure_ascii=False),number))
        return payload | {'event_id':number}


def get_attempt(attempt_id):
    with transaction() as conn:
        return _find(conn,attempt_id)


def has_unresolved_transport(conn,offer_id):
    if any(item['state'] in {'transport_unknown','transport_confirmed','ack_failed','ack_rejected'}
           for item in _history(conn).values() if item['binding']['offer_id']==offer_id):
        return True
    # A legacy transfer can be in flight before there is a publication row.
    return _legacy_pending(conn,offer_id)


class ResolutionError(AttemptError):
    """D09 refusal with a stable code; nothing was written."""
    def __init__(self,code):
        super().__init__(code);self.code=code


def event_time(conn,event_id):
    table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
    row=conn.execute(f'SELECT created_at FROM {table} WHERE id=?',(event_id,)).fetchone()
    return row[0] if row else None


def event_time_ro(event_id):
    """Creation time of one history event, read-only (None if unavailable)."""
    import sqlite3
    from modules.core import storage_paths
    path=storage_paths.foreign_offers_db_path() if _foreign() else storage_paths.idb_db_path()
    try:
        with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True,timeout=0)) as conn:
            return event_time(conn,event_id)
    except sqlite3.Error:return None


def _resolution_events(conn,item):
    table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
    column='foreign_offer_id' if _foreign() else 'offer_id'
    binding=item['binding']
    rows=conn.execute(f'SELECT id,payload_json FROM {table} WHERE event_type=? AND {column}=? AND portal_key=? ORDER BY id',
                      (RESOLUTION_TYPE,binding['offer_id'],binding['portal'])).fetchall()
    result=[]
    for number,raw in rows:
        payload=json.loads(raw)
        if isinstance(payload,dict) and payload.get('attempt_id')==item['attempt_id']:result.append((number,payload))
    return result


def resolve_attempt(attempt_id,*,outcome,evidence,decided_by,decided_at,idempotency_key,request_sha256,expected_event_id,validate):
    """D09: close an UNKNOWN/ACK_REJECTED attempt by APPENDING events; never sends, STARTs or acknowledges.

    One domain transaction under dictionary lock + (non-blocking) input lock: replay check, CAS on the last
    event, caller-supplied validation, audit event, state event (and the closed marker for closing outcomes).
    A returned dict with replayed=True means an identical earlier decision was found; nothing was written.
    """
    if outcome not in OUTCOME_STATE:raise ResolutionError('invalid_request')
    with transaction() as conn:
        item=_find(conn,attempt_id)
        for number,prior in _resolution_events(conn,item):
            if prior.get('idempotency_key')==idempotency_key:
                if prior.get('request_sha256')!=request_sha256:raise ResolutionError('idempotency_conflict')
                return item | {'replayed':True,'resolution_event_id':number}
        if item['state'] not in RESOLVABLE:raise ResolutionError('attempt_not_resolvable')
        if expected_event_id!=item['event_id']:raise ResolutionError('attempt_changed')
        reason=validate(conn,item)
        if reason:raise ResolutionError(reason)
        binding=item['binding']
        audit={'attempt_id':attempt_id,'from_state':item['state'],'outcome':outcome,'to_state':OUTCOME_STATE[outcome],
               'evidence':evidence,'decided_by':decided_by,'decided_at':decided_at,'idempotency_key':idempotency_key,
               'request_sha256':request_sha256,'expected_event_id':expected_event_id,
               'package_id':binding['package_id'],'zip_sha256':binding['zip_sha256'],'portal':binding['portal']}
        number=event(conn,binding['offer_id'],binding['portal'],RESOLUTION_TYPE,audit)
        meta={'outcome':outcome,'from_state':item['state'],'decided_by':decided_by,'decided_at':decided_at,'resolution_event_id':number}
        result=_append(conn,item|{'resolution':meta},OUTCOME_STATE[outcome],'resolved_'+outcome)
        return result | {'replayed':False,'resolution_event_id':number}


def unit_attempts_ro(subject,portal):
    """Read-only (mode=ro) attempts of one unit, newest first: {'state':'ok'|'unavailable','items':[...]}."""
    import sqlite3
    from modules.core import storage_paths
    path=storage_paths.foreign_offers_db_path() if _foreign() else storage_paths.idb_db_path()
    table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
    if not path.is_file():return {'state':'ok','items':[]}
    try:
        with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True,timeout=0)) as conn:
            conn.execute('PRAGMA query_only=ON')
            if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",(table,)).fetchone():
                return {'state':'ok','items':[]}
            conn.execute('BEGIN')
            history=list(_history(conn).values()) if _foreign() else list(_history(conn,subject['id'],portal).values())
    except (sqlite3.Error,AttemptError,ValueError,KeyError,TypeError):return {'state':'unavailable','items':[]}
    def match(item):
        b=item['binding']
        return b['portal']==portal and (b.get('subject')==subject or (subject['kind']=='foreign_offer' and subject['id'] in b.get('members',[]))
                                         or (not _foreign() and b['offer_id']==subject['id']))
    items=sorted((i for i in history if match(i)),key=lambda i:i['prepared_seq'],reverse=True)
    return {'state':'ok','items':items}


def _legacy_pending(conn,offer_id,portal=None):
    if _foreign(): return False  # legacy foreign path has no durable START; see trust boundary
    return conn.execute('''SELECT 1 FROM offer_portal_sync_events AS a
        WHERE a.offer_id=? AND (? IS NULL OR a.portal_key=?)
        AND a.event_type='legacy_attempt_started'
        AND NOT EXISTS (SELECT 1 FROM offer_portal_sync_events AS done
            WHERE done.offer_id=a.offer_id AND done.portal_key=a.portal_key
            AND done.event_type IN ('legacy_transport_confirmed','legacy_transport_failed')
            AND done.payload_json=a.payload_json) LIMIT 1''',(offer_id,portal,portal)).fetchone() is not None


def _start_in_transaction(conn,item,binding,*,settings,pre=None,qualification=None):
    """Shared START primitive: _current() exactly once, then UNKNOWN is written by the caller's commit.

    Legacy callers pass neither gate and keep the exact previous behaviour (a stale attempt raises).
    The trusted qualified entrypoint passes `pre` (cheap fence/control/identity checks before
    _current) and `qualification` (full business gate after it); a refusal returns can_send=False
    with a safe reason and writes nothing.
    """
    if item['state']!='prepared':return item | {'can_send':False}
    gated = pre is not None or qualification is not None
    if pre is not None:
        reason=pre(conn,item)
        if reason:return item | {'can_send':False,'reason':reason}
    if gated:
        try:_current(conn,item,settings)
        except AttemptError:return item | {'can_send':False,'reason':'attempt_not_current'}
    else:_current(conn,item,settings)
    if qualification is not None:
        reason=qualification(conn,item)
        if reason:return item | {'can_send':False,'reason':reason}
    return _append(conn,item,'transport_unknown') | {'can_send':True}


def start_transport(attempt_id,binding,*,settings=None):
    """Persist UNKNOWN before sending; only the first committed call may send.

    Lost response, crash or reconnect => can_send=False. Never infer failure
    from the absence of a transport result and never automatically retry FTP.
    """
    with transaction() as conn:
        item=_find(conn,attempt_id,binding)
        return _start_in_transaction(conn,item,binding,settings=settings)


def start_gated_transport(attempt_id,binding,*,pre,qualification,settings=None):
    """START with caller-supplied gates, in ONE transaction under dictionary lock and input_lock (can_send=True only after commit).

    `pre(conn,item)` runs before _current() and `qualification(conn,item)` after it; each returns None or a safe refusal reason
    (a refusal writes nothing). The trusted qualified entrypoint, export_start.start_qualified_transport, builds the gates.
    Server code only; never reachable from HTTP or the legacy RPC.
    """
    with transaction() as conn:
        item=_find(conn,attempt_id,binding)
        return _start_in_transaction(conn,item,binding,settings=settings,pre=pre,qualification=qualification)


def inspect_attempt(attempt_id,*,anchor_id=None,portal=None):
    """Read-only observation: mode=ro + query_only, no schema init, no locks, no ZIP checks.

    Returns {'state': found|absent|inconsistent|unavailable, 'attempt': item|None, 'reason': code|None}.
    """
    import sqlite3
    from modules.core import storage_paths
    if not isinstance(attempt_id,str) or not ID.fullmatch(attempt_id):
        raise AttemptError('Nieprawidłowy identyfikator próby.')
    path=storage_paths.foreign_offers_db_path() if _foreign() else storage_paths.idb_db_path()
    if not path.is_file():return {'state':'unavailable','attempt':None,'reason':'database_missing'}
    table='foreign_offer_portal_sync_events' if _foreign() else 'offer_portal_sync_events'
    try:
        with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True,timeout=0)) as conn:
            conn.execute('PRAGMA query_only=ON')
            if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",(table,)).fetchone():
                return {'state':'absent','attempt':None,'reason':'no_history_table'}
            conn.execute('BEGIN')
            history=_history(conn,anchor_id,portal) if anchor_id is not None and portal is not None else _history(conn)
    except sqlite3.Error:return {'state':'unavailable','attempt':None,'reason':'storage_unavailable'}
    except (AttemptError,ValueError,KeyError,TypeError):return {'state':'inconsistent','attempt':None,'reason':'history_inconsistent'}
    item=history.get(attempt_id)
    return {'state':'found','attempt':item,'reason':None} if item is not None else {'state':'absent','attempt':None,'reason':'attempt_not_found'}


def record_transport_result(attempt_id,binding,outcome):
    if outcome not in {'confirmed','failed','unknown'}:
        raise AttemptError('Nieprawidłowy wynik transportu.')
    desired={'confirmed':'transport_confirmed','failed':'transport_failed','unknown':'transport_unknown'}[outcome]
    with transaction() as conn:
        item=_find(conn,attempt_id,binding)
        if item['state']==desired:return item
        if item['state']!='transport_unknown':
            raise AttemptError('Wyniku zakończonej próby nie wolno nadpisać.')
        return _append(conn,item,desired)


def _current(conn,item,settings,*,allow_retired=False):
    binding=item['binding']
    if _revision(conn,binding['offer_id'])!=item['revision']:
        raise AttemptError('Dane zmieniono po przygotowaniu próby.')
    if _status(conn,binding)!=item['baseline']:
        raise AttemptError('Stan portalu zmienił się po przygotowaniu próby.')
    others=([other for other in _history(conn).values() if _same(other['binding'],binding)]
            if _foreign() else _history(conn,binding['offer_id'],binding['portal']).values())
    if any(other['prepared_seq']>item['prepared_seq'] for other in others):
        raise AttemptError('Istnieje nowsza próba dla tego portalu.')
    if not _foreign() and conn.execute('''SELECT 1 FROM offer_portal_sync_events WHERE offer_id=?
        AND portal_key=? AND event_type IN ('sync_state_set','legacy_attempt_started') AND id>? LIMIT 1''',
        (binding['offer_id'],binding['portal'],item['prepared_seq'])).fetchone():
        raise AttemptError('Ręcznie zmieniono stan portalu.')
    actual = (_package(binding['package_id'],settings,allow_retired=True)
              if allow_retired and not _foreign() else _package(binding['package_id'],settings))
    if actual!=binding:
        raise AttemptError('Wejścia lub artefakty paczki są nieaktualne.')


def _acknowledge(attempt_id,binding,*,settings=None):
    """Fresh validation + ordering + idempotency + state write under both locks."""
    with transaction() as conn:
        item=_find(conn,attempt_id,binding)
        if item['state']=='ack_completed':
            # Do not reapply an old add over a later delete (or manual state).
            return item | {'already_acknowledged':True}
        if item['state'] not in {'transport_confirmed','ack_failed'}:
            raise AttemptError('Brak potwierdzonego sukcesu transportu; ACK zabroniony.')
        try:
            _current(conn,item,settings,allow_retired=True)
        except ConsistencyError:
            return _append(conn,item,'ack_rejected','inputs_or_order_changed')
        if _foreign():
            from .foreign_attempt_inputs import acknowledge
            acknowledge(conn,binding)
        else:
            conn.execute('''INSERT INTO offer_portal_sync (offer_id,portal_key,
                is_published,needs_update,last_action,last_filename,last_bytes,
                last_error,last_uploaded_at,updated_at)
                VALUES (?,?,?,0,?,?,?,NULL,datetime('now'),datetime('now'))
                ON CONFLICT(offer_id,portal_key) DO UPDATE SET
                is_published=excluded.is_published,needs_update=0,
                last_action=excluded.last_action,last_filename=excluded.last_filename,
                last_bytes=excluded.last_bytes,last_error=NULL,
                last_uploaded_at=excluded.last_uploaded_at,updated_at=excluded.updated_at''',
                (binding['offer_id'],binding['portal'],int(binding['action']=='add'),
                 binding['action'],binding['zip_name'],binding['zip_size']))
        return _append(conn,item,'ack_completed')


def acknowledge_attempt(attempt_id,binding,*,settings=None):
    try:
        return _acknowledge(attempt_id,binding,settings=settings)
    except Exception as exc:
        # The transport result is already durable. Failure here never grants a
        # second send, including if the commit succeeded but its response was lost.
        try:
            with transaction() as conn:
                item=_find(conn,attempt_id,binding)
                if item['state']=='ack_completed':
                    return item | {'already_acknowledged':True}
                if item['state'] in {'transport_confirmed','ack_failed'}:
                    _append(conn,item,'ack_failed','ack_storage_or_verification_unavailable')
        except Exception:
            pass
        raise AttemptError('ACK failed or remains pending; do not resend FTP. Query the durable attempt.') from exc


# One lifecycle, separate existing data stores. Internal calls preserve context.
for _name in ('create_attempt','get_attempt','start_transport','start_gated_transport','inspect_attempt','record_transport_result','acknowledge_attempt','resolve_attempt','unit_attempts_ro','event_time_ro'):
    globals()[_name] = domain_api(globals()[_name])
