"""Foreign input revisions in existing events; one shared process/file lock.

SQLite triggers make business data and revision atomic, including raw SQL using
other connections. Bookkeeping/transport/ACK events never advance input revision.
Cross-database agent edits use the existing pre-write/completion pattern.
"""
from contextlib import closing
import hashlib
import json
import sqlite3
import uuid

from modules.core import storage_paths
from .input_consistency import input_lock, ConsistencyError

EVENT = 'foreign_input_revision_v2'
START = 'foreign_input_external_started_v2'
DONE = 'foreign_input_external_completed_v2'
FAILED = 'foreign_input_external_failed_v2'
TABLES = ('foreign_offers', 'foreign_developments', 'foreign_offer_images',
          'foreign_offer_features_raw', 'foreign_offer_export_warnings')
IGNORED = {'created_at', 'updated_at', 'needs_update', 'last_exported_at',
           'last_source_sync_at', 'last_source_change_at', 'source_payload_hash',
           'source_values_json', 'last_sync_run_id'}


class ForeignConnection(sqlite3.Connection):
    """Authorize before SQLite steps/BEGIN, not after acquiring its writer lock."""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._input_guard = None
        self.set_authorizer(self._authorize)

    def _authorize(self, action, first, second, database, source):
        writes = {sqlite3.SQLITE_INSERT, sqlite3.SQLITE_UPDATE, sqlite3.SQLITE_DELETE,
                  sqlite3.SQLITE_CREATE_TABLE, sqlite3.SQLITE_CREATE_INDEX,
                  sqlite3.SQLITE_CREATE_TRIGGER, sqlite3.SQLITE_ALTER_TABLE,
                  sqlite3.SQLITE_DROP_TABLE, sqlite3.SQLITE_DROP_TRIGGER,
                  sqlite3.SQLITE_DROP_INDEX, sqlite3.SQLITE_TRANSACTION, sqlite3.SQLITE_SAVEPOINT}
        if action in writes or action == sqlite3.SQLITE_PRAGMA and second is not None:
            if self._input_guard is None:
                guard = input_lock()
                try: guard.__enter__()
                except (ConsistencyError, OSError): return sqlite3.SQLITE_DENY
                self._input_guard = guard
        return sqlite3.SQLITE_OK

    def _release(self):
        guard, self._input_guard = self._input_guard, None
        if guard is not None: guard.__exit__(None, None, None)

    def commit(self):
        try: return super().commit()
        finally:
            if not self.in_transaction: self._release()

    def rollback(self):
        try: return super().rollback()
        finally:
            if not self.in_transaction: self._release()

    def close(self):
        try: return super().close()
        finally: self._release()

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            try: self.commit()
            except BaseException:
                self.rollback()
                raise
        else: self.rollback()
        return False


def definitions(conn):
    result = {}
    for table in TABLES:
        columns = [r[1] for r in conn.execute(f'PRAGMA table_info("{table}")')
                   if r[1] not in IGNORED or table == 'foreign_offer_export_warnings' and r[1] == 'created_at']
        if not columns: raise ConsistencyError('Brak schematu danych zagranicznych.')
        for action in ('INSERT', 'UPDATE', 'DELETE'):
            name = f'idb_foreign_v2_{table}_{action.lower()}'
            changed = ' OR '.join(f'OLD."{c}" IS NOT NEW."{c}"' for c in columns)
            condition = f'WHEN {changed}' if action == 'UPDATE' else ''
            # Existing table/FK, no synthetic offer or second history store.
            anchor = 'NEW.id' if table == 'foreign_offers' and action != 'DELETE' else '(SELECT MIN(id) FROM foreign_offers)'
            result[name] = f'''CREATE TRIGGER IF NOT EXISTS {name} AFTER {action} ON {table}
                {condition} BEGIN
                INSERT INTO foreign_offer_portal_sync_events(foreign_offer_id,portal_key,event_type,payload_json)
                SELECT {anchor},NULL,'{EVENT}','{{"table":"{table}","action":"{action}"}}'
                WHERE {anchor} IS NOT NULL;
                END'''
    result['idb_foreign_v2_delete_guard'] = f'''CREATE TRIGGER IF NOT EXISTS idb_foreign_v2_delete_guard
        BEFORE DELETE ON foreign_offers BEGIN
        SELECT CASE WHEN EXISTS (SELECT 1 FROM foreign_offer_portal_sync_events s
          WHERE s.event_type='{START}' AND NOT EXISTS
          (SELECT 1 FROM foreign_offer_portal_sync_events d WHERE d.event_type='{DONE}' AND d.payload_json=s.payload_json))
          THEN RAISE(ABORT,'Unresolved foreign input write') END;
        SELECT CASE WHEN EXISTS (SELECT 1 FROM foreign_offer_portal_sync_events s
          WHERE s.event_type='export_transport_open_v2' AND NOT EXISTS
          (SELECT 1 FROM foreign_offer_portal_sync_events d
           WHERE d.event_type='export_transport_closed_v2' AND d.payload_json=s.payload_json AND d.id>s.id))
          THEN RAISE(ABORT,'Unresolved foreign transport') END;
        END'''
    return result


def _normalized(sql):
    return ' '.join(sql.replace('IF NOT EXISTS ', '').split()).rstrip(';')


def install_guards(conn, *, allow_upgrade=False):
    missing=[];replace=[]
    for name, sql in definitions(conn).items():
        current = conn.execute('SELECT sql FROM sqlite_master WHERE type=? AND name=?', ('trigger', name)).fetchone()
        if current and _normalized(current[0]) != _normalized(sql):
            if not allow_upgrade:raise ConsistencyError('Niezgodna ochrona rewizji zagranicznych.')
            replace.append(name);missing.append(sql)
        if not current: missing.append(sql)
    if missing:
        # Guard restoration must invalidate old artifacts, even if a privileged
        # maintenance writer modified A->B->A while a guard was missing.
        conn.execute('SAVEPOINT foreign_guard_install')
        try:
            for name in replace:conn.execute(f'DROP TRIGGER "{name}"')
            for sql in missing: conn.execute(sql)
            conn.execute('''INSERT INTO foreign_offer_portal_sync_events(foreign_offer_id,event_type,payload_json)
                SELECT MIN(id),?,? FROM foreign_offers HAVING MIN(id) IS NOT NULL''',
                (EVENT,'{"table":"schema","action":"install"}'))
            conn.execute('RELEASE foreign_guard_install')
        except BaseException:
            conn.execute('ROLLBACK TO foreign_guard_install')
            conn.execute('RELEASE foreign_guard_install')
            raise


def revision(conn):
    expected = definitions(conn)
    actual = {r[0]: r[1] for r in conn.execute("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'idb_foreign_v2_%'")}
    if set(actual) != set(expected) or any(_normalized(actual[n]) != _normalized(sql) for n, sql in expected.items()):
        raise ConsistencyError('Brak kompletnej ochrony rewizji zagranicznych.')
    pending=conn.execute('''SELECT 1 FROM foreign_offer_portal_sync_events s
        WHERE s.event_type IN (?,?) AND NOT EXISTS
        (SELECT 1 FROM foreign_offer_portal_sync_events d WHERE d.event_type=?
         AND d.payload_json=s.payload_json AND d.id>s.id) LIMIT 1''',(START,FAILED,DONE)).fetchone()
    if pending: raise ConsistencyError('Niedokończona lub nieudana zmiana danych agenta.')
    last=conn.execute('''SELECT COALESCE(MAX(id),0) FROM foreign_offer_portal_sync_events
        WHERE event_type IN (?,?,?,?)''',(EVENT,START,DONE,FAILED)).fetchone()[0]
    # Global scope is intentionally conservative: unrelated foreign edits also
    # stale an artifact; excluded project members and membership ABA are covered.
    value = {'schema': 2, 'last_input_event': last,
             'guard': hashlib.sha256(json.dumps(expected, sort_keys=True).encode()).hexdigest()}
    return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()


def _agent_projections(conn):
    """Only contact values actually emitted by both foreign portal renderers.

    Reuse their override/fallback/normalization rules; no packages or media I/O.
    Caller holds the cross-database input lock throughout the agent mutation.
    """
    from InvestmentManager.export_engine import foreign_offers_export as engine, runtime_paths
    root = storage_paths.foreign_offers_db_path().parent.parent.resolve()
    conn.row_factory = sqlite3.Row
    result = {}
    portals = {}
    for row in conn.execute('SELECT foreign_offer_id,portal_key FROM foreign_offer_portal_sync WHERE is_published=1'):
        if row['portal_key'] in {'domiporta', 'tabelaofert'}:
            portals.setdefault(row['foreign_offer_id'], []).append(row['portal_key'])
    with runtime_paths.use(runtime_paths.LocalInputs(root)):
        for row in conn.execute('SELECT * FROM foreign_offers WHERE id IN '
                                '(SELECT foreign_offer_id FROM foreign_offer_portal_sync WHERE is_published=1)'):
            contact = engine._resolve_agent(row)
            for portal in portals.get(row['id'], ()):
                result[(row['id'], portal)] = {k: contact[k] for k in ('name', 'email', 'phone')}
    return result


def external_start():
    path = storage_paths.foreign_offers_db_path()
    if not path.is_file(): return None  # no foreign artifacts can exist yet
    with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as conn:
        if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='foreign_offers'").fetchone(): return None
        if not conn.execute('SELECT 1 FROM foreign_offers LIMIT 1').fetchone(): return None
    from InvestmentManager.foreign_offers_store import open_foreign_offers_connection
    marker = json.dumps({'mutation_id': uuid.uuid4().hex}, sort_keys=True)
    with closing(open_foreign_offers_connection()) as conn:
        # Legacy domestic-only callers can still edit an agent safely before
        # visiting the foreign CRM page. Install missing guards, then premark.
        install_guards(conn)
        conn.commit()
        revision(conn)  # fail before agent modification if guards/history fail
        from .input_consistency import _held
        current = _held.get()
        if current is None:
            raise ConsistencyError('Agent mutation requires input lock')
        current.setdefault('foreign_before', {})[marker] = _agent_projections(conn)
        conn.execute('BEGIN IMMEDIATE')
        conn.execute('''INSERT INTO foreign_offer_portal_sync_events(foreign_offer_id,event_type,payload_json)
            SELECT MIN(id),?,? FROM foreign_offers''', (START, marker))
        conn.commit()
    return marker


def external_finish(marker, failed):
    from InvestmentManager.foreign_offers_store import open_foreign_offers_connection
    with closing(open_foreign_offers_connection()) as conn:
        from .input_consistency import _held
        current = _held.get()
        if current is None or marker not in current.get('foreign_before', {}):
            raise ConsistencyError('Missing agent mutation projection')
        before = current['foreign_before'][marker]
        after = _agent_projections(conn)
        conn.execute('BEGIN IMMEDIATE')
        for (identifier, portal), contact in after.items():
            if before.get((identifier, portal)) != contact:
                conn.execute('UPDATE foreign_offer_portal_sync SET needs_update=1 '
                             'WHERE foreign_offer_id=? AND portal_key=? AND is_published=1', (identifier, portal))
                conn.execute('UPDATE foreign_offers SET needs_update=1 WHERE id=?', (identifier,))
        conn.execute('''INSERT INTO foreign_offer_portal_sync_events(foreign_offer_id,event_type,payload_json)
            SELECT MIN(id),?,? FROM foreign_offers''', (FAILED if failed else DONE, marker))
        conn.commit()
