"""Foreign data adapter for the shared export_attempts state machine.

No transport or independent attempt lifecycle. All calls run under input_lock.
"""
from contextlib import contextmanager, closing
import hashlib

from . import domestic_package_catalog as catalog
from .foreign_consistency import revision
from .input_consistency import ConsistencyError


@contextmanager
def connection():
    from InvestmentManager.foreign_offers_store import open_foreign_offers_connection
    from modules.core import storage_paths
    if not storage_paths.foreign_offers_db_path().is_file():
        raise ConsistencyError('Foreign database unavailable')
    with closing(open_foreign_offers_connection()) as conn:
        try:
            yield conn
        except BaseException:
            conn.rollback()
            raise


def event(conn, offer_id, portal, kind, payload):
    from InvestmentManager.foreign_offers_store import _insert_portal_event
    _insert_portal_event(conn, offer_id, portal, kind, payload)
    return conn.execute('SELECT last_insert_rowid()').fetchone()[0]


def package(package_id, settings):
    from .foreign_contract import validate_manifest
    root, base = catalog._root('foreign')
    result = catalog.verify_package(package_id, domain='foreign', settings=settings)
    if result['state'] != 'READY':
        raise ConsistencyError('Foreign package is not READY')
    with catalog._open(base/package_id/'manifest.json', base) as stream:
        raw = stream.read(catalog.MAX_MANIFEST+1)
    item = catalog._manifest(raw, package_id, 'foreign')
    validate_manifest(item)
    if item != result['manifest']:
        raise ConsistencyError('Manifest changed')
    return {k: item[k] for k in ('domain', 'package_id', 'subject', 'members', 'portal',
            'transport_profile', 'action', 'input_fingerprint', 'input_revision',
            'zip_sha256', 'zip_size', 'zip_name')} | {
                'offer_id': item['members'][0],  # history FK anchor, never subject identity
                'manifest_sha256': hashlib.sha256(raw).hexdigest()}


def status(conn, binding):
    result = []
    for offer in binding['members']:
        row = conn.execute('''SELECT is_published,needs_update,last_action,last_filename,
            last_bytes,last_error,last_uploaded_at,updated_at FROM foreign_offer_portal_sync
            WHERE foreign_offer_id=? AND portal_key=?''', (offer, binding['portal'])).fetchone()
        seq = conn.execute('''SELECT COALESCE(MAX(id),0) FROM foreign_offer_portal_sync_events
            WHERE foreign_offer_id=? AND portal_key=? AND event_type IN
            ('uploaded','deleted','sync_state_set','legacy_attempt_started')''',
            (offer, binding['portal'])).fetchone()[0]
        result.append([offer, list(row) if row is not None else None, seq])
    return result


def acknowledge(conn, binding):
    # All members and aggregate flags commit with the one attempt event.
    for offer in binding['members']:
        conn.execute('''INSERT INTO foreign_offer_portal_sync
            (foreign_offer_id,portal_key,is_published,needs_update,last_action,last_filename,
             last_bytes,last_error,last_uploaded_at,updated_at)
            VALUES (?,?,?,0,?,?,?,NULL,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
            ON CONFLICT(foreign_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=CURRENT_TIMESTAMP,updated_at=CURRENT_TIMESTAMP''',
            (offer,binding['portal'],int(binding['action']=='add'),binding['action'],
             binding['zip_name'],binding['zip_size']))
        conn.execute('''UPDATE foreign_offers SET needs_update=CASE WHEN EXISTS
            (SELECT 1 FROM foreign_offer_portal_sync WHERE foreign_offer_id=? AND needs_update=1)
            THEN 1 ELSE 0 END WHERE id=?''', (offer,offer))
        if binding['action']=='add':
            conn.execute('UPDATE foreign_offers SET last_exported_at=CURRENT_TIMESTAMP WHERE id=?',(offer,))
        event(conn,offer,binding['portal'],'uploaded' if binding['action']=='add' else 'deleted',
              {'mode':binding['action'],'package_id':binding['package_id']})
