"""One fail-closed, process-shared lock for domestic inputs and export ACK.

Lock order: this lock, then a single SQLite connection. Never wait for this
lock while holding a database transaction. No network or import-time I/O.
"""
from contextlib import contextmanager, closing
from contextvars import ContextVar
from functools import wraps
import json
import errno
import os
from pathlib import Path
import sqlite3
import stat
import threading
import uuid

from modules.core import storage_paths
from . import domestic_batch_limits as limits
from . import export_performance as performance

_held = ContextVar('domestic_input_lock', default=None)


class ConsistencyError(RuntimeError):
    pass


class LockBusy(ConsistencyError):
    """The non-blocking input lock is held elsewhere. Raised before any write, so a
    retry is safe. Same base type and message as before, hence unchanged legacy mapping."""


@contextmanager
def input_lock():
    limits.check('input_lock')
    owner = (os.getpid(), threading.get_ident())
    current = _held.get()
    if current is not None and current['owner'] == owner:
        yield current
        return
    folder = storage_paths.idb_db_path().parent.resolve()
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / '.export-inputs.lock'
    if path.is_symlink() or (hasattr(path, 'is_junction') and path.is_junction()):
        raise ConsistencyError('Niebezpieczny plik blokady eksportu.')
    fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0), 0o600)
    acquired = False
    token = None
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            raise ConsistencyError('Nieprawidłowy plik blokady eksportu.')
        with performance.stage('input_lock.wait'):
            if os.name == 'nt':
                import msvcrt
                if os.fstat(fd).st_size == 0:
                    os.write(fd, b'0')
                os.lseek(fd, 0, os.SEEK_SET)
                msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
            elif os.name == 'posix':
                import fcntl
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            else:
                raise ConsistencyError('System nie obsługuje wymaganej blokady eksportu.')
        acquired = True
        current = {'owner': owner, 'writes': [], 'failed': False, 'depth': 0}
        token = _held.set(current)
        limits.check('input_lock')
        with performance.stage('input_lock.held'):
            yield current
    except OSError as exc:
        if limits.current() is not None and not acquired and exc.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
            raise limits.BatchStop('lock_busy', 'input_lock') from exc
        if not acquired and exc.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
            raise LockBusy('Dane eksportu są zajęte lub blokada jest niedostępna. Ponów operację.') from exc
        raise ConsistencyError('Dane eksportu są zajęte lub blokada jest niedostępna. Ponów operację.') from exc
    finally:
        if token is not None:
            _held.reset(token)
        if acquired:
            if os.name == 'nt':
                os.lseek(fd, 0, os.SEEK_SET)
                msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
            else:
                fcntl.flock(fd, fcntl.LOCK_UN)
        os.close(fd)


@contextmanager
def state_connection():
    # Deliberately no connection pool; never retain a DB lock while acquiring
    # the shared lock. Schema is the already existing portal-state schema.
    from .portal_sync_state import _ensure_sync_tables
    with closing(sqlite3.connect(storage_paths.idb_db_path())) as conn:
        _ensure_sync_tables(conn)
        conn.commit()
        try:
            yield conn
        except BaseException:
            conn.rollback()
            raise


def event(conn, offer_id, portal, kind, payload):
    from .portal_sync_state import _insert_event
    _insert_event(conn, offer_id=int(offer_id), portal_key=portal, event_type=kind, payload=payload)
    return conn.execute('SELECT last_insert_rowid()').fetchone()[0]


def agent_export_changed(agent_id, values):
    """Account/security fields never start an export mutation."""
    fields = tuple(values)
    if not fields or not set(fields) <= {'first_name', 'last_name', 'email', 'phone', 'license'}:
        raise ValueError('Unsupported agent projection')
    path = storage_paths.agents_db_path()
    with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as conn:
        row = conn.execute('SELECT ' + ','.join(fields) + ' FROM agents_v2 WHERE id=?', (agent_id,)).fetchone()
    def text(value, field):
        value = '' if value is None else str(value)
        return value.rstrip() if field == 'license' else value
    return row is not None and any(text(row[i], field) != text(values[field], field)
                                   for i, field in enumerate(fields))


def table_inputs(cursor, db_key, table, column, where, args=()):
    """Limit DB Shell invalidation to actual export input rows."""
    table, column = table.lower(), column.lower()
    if db_key == 'agents' and table == 'agents_v2':
        if column not in {'id', 'first_name', 'last_name', 'email', 'phone', 'license'}:
            return
        for (agent_id,) in cursor.execute('SELECT id FROM agents_v2 WHERE ' + where, args).fetchall():
            write_inputs(agent_id=agent_id, media=False)
    elif db_key == 'idb' and table in {'estatedata', 'localization'}:
        columns = [r[1].lower() for r in cursor.execute(f'PRAGMA table_info("{table}")')]
        if column not in columns[:37 if table == 'estatedata' else 6]:
            return
        ids = [r[0] for r in cursor.execute(f'SELECT ID FROM "{table}" WHERE ' + where, args)]
        write_inputs(offer_ids=ids, media=False)


def write_inputs(*, offer_ids=None, agent_id=None, all_offers=False, media=True):
    """Durably mark BEFORE the first write; leave an unfinished event on crash.

    Call only inside serialized_write. A failed/partial mutation deliberately
    blocks ACK until explicitly repaired; SQLite cannot roll back media files.
    """
    current = _held.get()
    if current is None or current['owner'] != (os.getpid(), threading.get_ident()):
        raise ConsistencyError('Zapis danych wymaga wspólnej blokady.')
    if (agent_id is not None or all_offers) and not current.get('foreign_writes'):
        from .foreign_consistency import external_start
        marker = external_start()
        if marker is not None: current.setdefault('foreign_writes', []).append(marker)
    with state_connection() as conn:
        ids = {int(i) for i in (offer_ids or [])}
        exists = conn.execute("SELECT 1 FROM sqlite_master WHERE lower(name)='estatedata'").fetchone()
        if exists and (agent_id is not None or all_offers):
            query = 'SELECT ID FROM EstateData'
            args = ()
            if not all_offers:
                query += ' WHERE ID_agenta=?'
                args = (agent_id,)
            ids.update(int(row[0]) for row in conn.execute(query, args))
        if all_offers:
            ids.update(row[0] for row in conn.execute('SELECT DISTINCT offer_id FROM offer_portal_sync'))
        # A global mutation (administrative SQL) also guards future/removed IDs.
        if all_offers:
            ids.add(0)
        for offer_id in sorted(ids):
            mutation = uuid.uuid4().hex
            if offer_id not in current.setdefault('before', {}):
                from .domestic_export_inputs import snapshot, dictionary_responses
                if 'projection_responses' not in current:
                    current['projection_responses'] = dictionary_responses()
                root = storage_paths.idb_db_path().parent.parent.resolve()
                relevant = conn.execute('SELECT 1 FROM offer_portal_sync WHERE offer_id=? AND (is_published=1 OR needs_update=1) LIMIT 1', (offer_id,)).fetchone()
                relevant = relevant or conn.execute("SELECT 1 FROM offer_portal_sync_events WHERE offer_id=? AND event_type='export_attempt_v1' LIMIT 1", (offer_id,)).fetchone()
                if offer_id and relevant:
                    current.setdefault('compare', set()).add(offer_id)
                current.setdefault('media_scope', {})[offer_id] = media
                current['before'][offer_id] = snapshot(root, offer_id, responses=current['projection_responses'], include_media=media) if offer_id in current.get('compare', ()) else None
            elif media and not current['media_scope'][offer_id]:
                raise ConsistencyError('Nie można rozszerzyć zakresu rozpoczętego zapisu.')
            event(conn,offer_id,None,'input_write_started',{'mutation_id':mutation})
            current['writes'].append((offer_id,mutation))
        conn.commit()


def write_failed():
    current = _held.get()
    if current is not None:
        current['failed'] = True


def serialized_write(function=None, *, dry_run=False):
    """Keep the process lock across DB, file operations and the dirty marker."""
    if function is None:
        return lambda view: serialized_write(view,dry_run=dry_run)
    @wraps(function)
    def wrapped(*args, **kwargs):
        # Opt-in only for the existing read-only image-tool contract.
        if dry_run and kwargs.get('dry_run') is True:
            return function(*args, **kwargs)
        with input_lock() as current:
            outermost = current['depth'] == 0
            current['depth'] += 1
            try:
                result = function(*args, **kwargs)
                status = result[1] if isinstance(result,tuple) and len(result)>1 and isinstance(result[1],int) else getattr(result,'status_code',200)
                if status >= 400 or isinstance(result,dict) and result.get('errors',0):
                    current['failed'] = True
                return result
            except BaseException:
                current['failed'] = True
                raise
            finally:
                current['depth'] -= 1
                writes = current['writes'] if outermost else []
                if writes:
                    with state_connection() as conn:
                        for offer_id,mutation in writes:
                            changed = set()
                            if offer_id in current.get('compare', ()):
                                from .domestic_export_inputs import snapshot, changed_portals
                                root = storage_paths.idb_db_path().parent.parent.resolve()
                                changed = changed_portals(current['before'][offer_id], snapshot(root, offer_id, responses=current['projection_responses'], include_media=current['media_scope'][offer_id]))
                                from .portal_sync_state import _utcnow_iso
                                pending = {}
                                for portal, raw in conn.execute("SELECT portal_key,payload_json FROM offer_portal_sync_events WHERE offer_id=? AND event_type='export_attempt_v1' ORDER BY id", (offer_id,)):
                                    payload = json.loads(raw)
                                    pending[payload['attempt_id']] = (portal, payload['state'])
                                targets = {p for p, phase in pending.values() if phase not in {'ack_completed','transport_failed','resolved_not_published','resolved_superseded','resolved_obsolete'}}   # == export_attempts closed states
                                targets.update(r[0] for r in conn.execute('SELECT portal_key FROM offer_portal_sync WHERE offer_id=? AND (is_published=1 OR needs_update=1)', (offer_id,)))
                                for portal in changed & targets:
                                    conn.execute("""INSERT INTO offer_portal_sync
                                        (offer_id,portal_key,is_published,needs_update,updated_at)
                                        VALUES (?,?,0,1,?) ON CONFLICT(offer_id,portal_key)
                                        DO UPDATE SET needs_update=1,updated_at=excluded.updated_at""",
                                        (offer_id, portal, _utcnow_iso()))
                            event(conn,offer_id,None,'input_write_failed' if current['failed'] else 'input_write_completed',
                                  {'mutation_id':mutation, 'changed_portals':sorted(changed)})
                        conn.commit()
                if outermost:
                    from .foreign_consistency import external_finish
                    for marker in current.get('foreign_writes', []):
                        external_finish(marker, current['failed'])
    return wrapped


def guarded_route(function):
    """Preserve access decorators outside this wrapper; failures never succeed."""
    protected = serialized_write(function)
    @wraps(function)
    def wrapped(*args, **kwargs):
        from flask import jsonify
        try:
            return protected(*args, **kwargs)
        except (ConsistencyError,sqlite3.Error,OSError):
            return jsonify({'error':'Nie zapisano spójnej zmiany. Dane są zajęte lub wymagają kontroli synchronizacji.'}),409
    return wrapped


def input_revision(conn, offer_id):
    """Return revision and reject every unresolved/failed input mutation."""
    active = set()
    revision = 0
    for number,kind,raw in conn.execute('''SELECT id,event_type,payload_json
        FROM offer_portal_sync_events WHERE offer_id IN (0,?)
        AND event_type LIKE 'input_write_%' ORDER BY id''',(offer_id,)):
        payload = json.loads(raw)
        mutation = payload['mutation_id']
        if kind == 'input_write_started':
            active.add(mutation)
        elif kind == 'input_write_failed':
            active.add(mutation)
        elif kind == 'input_write_completed':
            active.discard(mutation)
        revision = number
    if active:
        raise ConsistencyError('Niedokończony zapis wejść eksportu wymaga kontroli i naprawy.')
    return revision
