"""Explicit, bounded domestic preparation; no worker, transport or CRM writes."""
from . import domestic_sets as sets, domestic_package_catalog as catalog
from . import domestic_dictionaries as dictionaries, sync_tasks as queue
from . import domestic_batch_limits as limits
from . import domestic_batch_timing as timing


def plan():
    try:
        with limits.scope():
            root, _ = catalog._root()
            with queue._read(root/'databases/IDB.db') as conn:
                offers = queue._rows(conn, 'SELECT ID FROM EstateData ORDER BY CAST(ID AS INTEGER)')
            limits.check('plan_complete')
            # Strings preserve SQLite identifiers above JavaScript's safe range.
            return {'offer_ids': [str(int(row['ID'])) for row in offers], 'total': len(offers)}
    except limits.BatchStop as exc:
        raise catalog.CatalogError(str(exc), 413 if exc.code == 'database_limit' else 503) from exc


@timing.measured('qualification', action_arg=2)
def _qualification(root, offer_id, action=None):
    limits.check('qualification')
    # Use all history, not only the latest task: an older unresolved attempt
    # must not be hidden by a subsequent record. Read-only, no schema creation.
    with queue._read(root/'databases/IDB.db') as conn:
        if queue._table(conn, 'offer_portal_sync_events'):
            if conn.execute('SELECT COUNT(*) FROM offer_portal_sync_events').fetchone()[0] > queue.MAX_EVENTS:
                raise ValueError('Operator queue history limit exceeded')
            if queue.attempts.has_unresolved_transport(conn, offer_id):
                return [], {'code': 'unresolved_operation', 'message': 'Transport lub ACK wymaga uzgodnienia.'}
    # A prepared attempt has never crossed START. It must remain visible in the
    # operator queue, but cannot block preparing/current-checking a package for
    # a new job. Started attempts are still rejected by the guard above.
    tasks = queue._domestic(root, offer_id=offer_id, ignore_prepared=True)
    if any(task['issue'] or task['category'] == 'error' for task in tasks):
        return [], {'code': 'needs_intervention', 'message': 'Kolejka wymaga interwencji; nie zastąpiono zestawów.',
                    'reasons': sorted({task['issue'] or task['transport_state'] for task in tasks
                                       if task['issue'] or task['category'] == 'error'})}
    tasks = [task for task in tasks if task['category'] in ('new', 'update', 'withdraw')]
    if action is not None and not any(task['action'] == action for task in tasks):
        return [], {'code': 'qualification_changed', 'message': 'Operacja nie jest już wymagana przez kolejkę.'}
    return tasks, None


def _guard(root, offer_id, action):
    return _qualification(root, offer_id, action)[1]


def _completed_portals(root, pointer, tasks):
    targets = {(task['portal'], pointer['packages'].get(task['portal'])) for task in tasks
               if task['action'] == pointer['action']}
    with queue._read(root/'databases/IDB.db') as conn:
        history = queue._history(conn, 'domestic')
    return sorted({item['binding']['portal'] for item in history
                   if item['state'] in queue.attempts.PACKAGE_CONSUMED
                   and item['binding']['offer_id'] == pointer['offer_id']
                   and item['binding']['action'] == pointer['action']
                   and (item['binding']['portal'], item['binding']['package_id']) in targets})


def _manual_result(result, pointer, portals):
    return result | {'code': 'manual_preparation_required', 'generation_id': pointer['generation_id'],
                     'portals': portals,
                     'message': 'Wymagana operacja ma już ACK dla bieżącej paczki (albo paczka została użyta w próbie zamkniętej rozstrzygnięciem D09 „nie opublikowano”). W panelu Paczki eksportowe otwórz sekcję Interwencja operatora i przygotuj nowy zestaw dla tej oferty i operacji; nie ponawiaj starej paczki.'}


def _process_set(root, base, offer_id, action, settings, *, _result=None):
    limits.check('process_set')
    result = _result if _result is not None else {'action': action, 'prepared': False, 'verified': False, 'skipped_current': False}
    with sets.locked():
        tasks, blocked = _qualification(root, offer_id, action)
        if blocked:
            return result | blocked
        pointer = sets.current(base, offer_id, action)
        complete = pointer is not None and set(pointer['packages']) == set(sets.portals_for_offer(root, offer_id, action))
        if complete:
            with timing.stage('existing_set_check', action=action):
                saved = sets._row(base, pointer)
                if saved['state'] == 'READY':
                    # READY is historical. Check the same live rules as verify_set,
                    # without rewriting its timestamp or trusting stale context/ZIP.
                    checks = []
                    for portal, pid in pointer['packages'].items():
                        with timing.stage('verify_portal', action=action, portal=portal):
                            checks.append(catalog._verify_package(pid, settings=settings))
                    states = {row['state'] for row in checks}
                    if states == {'READY'}:
                        completed = _completed_portals(root, pointer, tasks)
                        if completed:
                            return _manual_result(result, pointer, completed)
                        return result | {'code': 'current', 'skipped_current': True,
                                         'generation_id': pointer['generation_id']}
                else:
                    checked = sets.verify_set(offer_id, action, generation_id=pointer['generation_id'],
                                              settings=settings, refresh_dictionaries=False)
                    if checked.get('save_errors'):
                        return result | {'code': 'verification_save_failed',
                                         'message': 'Nie zapisano wyników weryfikacji; nie zastąpiono zestawu.'}
                    states = {row['state'] for row in checked['items']}
                    if states == {'READY'} and not checked.get('save_errors'):
                        completed = _completed_portals(root, pointer, tasks)
                        if completed:
                            return _manual_result(result | {'verified': True}, pointer, completed)
                        return result | {'code': 'verified', 'verified': True,
                                         'generation_id': pointer['generation_id']}
                if states - {'READY', 'STALE'}:
                    return result | {'code': 'verification_blocked',
                        'message': 'Kontrola istniejącego zestawu nie powiodła się; nie zastąpiono go.',
                        'states': sorted(states), 'diagnostics': checks if saved['state'] == 'READY' else checked['items']}
    # Do not retain the input lock or any edit transaction across generation.
    def activation_guard():
        blocked = _guard(root, offer_id, action)
        if blocked:
            return blocked
        if sets.current(base, offer_id, action) != pointer:
            return {'code': 'set_changed',
                    'message': 'Inny proces zmienił zestaw. Nie zastąpiono go; ponowne uruchomienie sprawdzi aktualny stan.'}
    try:
        prepared = sets.prepare_set(offer_id, action, settings=settings,
                                   _guard=activation_guard, _bounded_inputs=True)
    except catalog.preparation.PreparationError as exc:
        return result | {'code': exc.outcome if exc.outcome == 'input_limit' else 'preparation_failed',
                         'message': str(exc)}
    if not prepared['replaced']:
        return result | (prepared.get('block_reason') or {
            'code': 'input_limit' if prepared.get('outcome') == 'input_limit' else 'preparation_failed',
            'message': prepared.get('error', 'Nie przygotowano kompletnego zestawu.'),
            'portal_results': prepared['portal_results']})
    result.update(prepared=True, generation_id=prepared['generation_id'])
    limits.check('verify_activated_set')
    with sets.locked():
        blocked = _guard(root, offer_id, action)
        if blocked:
            return result | blocked
        with timing.stage('verify_new_set', action=action):
            checked = sets.verify_set(offer_id, action, generation_id=prepared['generation_id'],
                                      settings=settings, refresh_dictionaries=False)
    if checked['state'] != 'READY' or checked.get('save_errors'):
        return result | {'code': 'verification_failed', 'message': 'Nie potwierdzono trwałej weryfikacji zestawu.',
                         'state': checked['state'], 'items': checked['items']}
    return result | {'code': 'prepared_verified', 'verified': True}


def _process_offer(offer_id, *, settings=None):
    sets._selection(offer_id, 'add')
    result = {'offer_id': offer_id, 'sets': [], 'code': 'no_action'}
    try:
        root, base = catalog._root()
        for name in ('IDB.db', 'agents.db'):
            path = root/'databases'/name
            if path.exists():limits.database(path)
        with sets.locked():
            tasks, blocked = _qualification(root, offer_id)
        if blocked:
            return result | blocked
        actions = sorted({task['action'] for task in tasks})
        if not actions:
            return result
        # Existing bounded public dictionary cache, never under the input lock.
        with timing.stage('dictionaries'):
            _, dictionary_context = dictionaries.dictionary_inputs('domiporta')
        if any(item['status'] != 'available' for item in dictionary_context):
            return result | {'code': 'dictionary_unavailable',
                'message': 'Nie uzyskano kompletnych słowników Domiporta (błąd odczytu, timeout lub niepoprawna odpowiedź). Nie rozpoczęto przygotowania zestawów. Ponów po wygaśnięciu istniejącego cache błędów (do 5 minut).'}
        for action in actions:
            row = {'action': action, 'prepared': False, 'verified': False, 'skipped_current': False}
            result['sets'].append(row)
            try:
                row.update(_process_set(root, base, offer_id, action, settings, _result=row))
            except limits.BatchStop as exc:
                row.update(exc.result())
                break
            except Exception as exc:
                try:
                    limits.raise_if_locked(exc)
                except limits.BatchStop as stop:
                    row.update(stop.result())
                    break
                row.update(code='set_failed', message='Nie można bezpiecznie przygotować lub zweryfikować zestawu.')
        result['code'] = 'processed'
    except Exception as exc:
        limits.raise_if_locked(exc)
        result.update(code='offer_failed', message='Nie można bezpiecznie przeanalizować oferty.')
    return result


def process_offer(offer_id, *, settings=None):
    with timing.capture() as timings:
        with limits.scope():
            try:
                result = _process_offer(offer_id, settings=settings)
            except limits.BatchStop as exc:
                result = {'offer_id': offer_id, 'sets': [], **exc.result()}
    return result | {'timings': timings}
