"""Authoritative read-only operator queue over existing publication/attempt state.

No generation, dictionary downloads, transport, schema initialization or ACK.
The queue is a snapshot, never permission to send; the existing handoff/start
checks remain mandatory. No publication inference from offer status or ZIPs.
"""
from collections import namedtuple
from contextlib import contextmanager, closing
from datetime import datetime, timezone
import sqlite3
import hashlib
import json

from modules.core import storage_paths
from . import domestic_sets as sets, domestic_package_catalog as catalog
from . import domestic_packages as domestic, export_attempts as attempts
from .input_consistency import input_revision
from . import domestic_batch_limits as limits
from . import export_performance as performance
from . import domestic_storage as storage

VERSION = 1
MAX_OFFERS = 5000
MAX_EVENTS = 100000
UNRESOLVED = {'transport_unknown', 'transport_confirmed', 'ack_failed', 'ack_rejected'}
CATEGORIES = ('new', 'update', 'withdraw', 'error')


def _table(conn, name):
    return conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)).fetchone() is not None


@contextmanager
def _read(path):
    with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro', uri=True, **limits.sqlite_options())) as conn:
        limits.database(path, conn)
        conn.row_factory = sqlite3.Row
        conn.execute('PRAGMA query_only=ON')
        conn.execute('BEGIN')
        yield conn


def _rows(conn, query):
    rows = conn.execute(query+' LIMIT ?', (MAX_OFFERS+1,)).fetchall()
    if len(rows) > MAX_OFFERS:
        raise ValueError('Operator queue offer limit exceeded')
    return [dict(row) for row in rows]


def _history(conn, domain, *, ignore_prepared=False, offer_id=None):
    """Attempt history snapshot. ignore_prepared drops attempts that never started (business-need view)."""
    table = 'foreign_offer_portal_sync_events' if domain == 'foreign' else 'offer_portal_sync_events'
    if not _table(conn, table):
        return []
    if conn.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] > MAX_EVENTS:
        raise ValueError('Operator queue history limit exceeded')
    token = attempts._domain.set(domain)
    try:
        items = list(attempts._history(conn, offer_id).values())
    finally:
        attempts._domain.reset(token)
    if ignore_prepared:
        items = [item for item in items if item['state'] != 'prepared']
    return items


def _by_pair(history):
    latest, completed = {}, {}
    for item in sorted(history, key=lambda row: row['prepared_seq']):
        binding = item['binding']
        for offer in binding.get('members', [binding['offer_id']]):
            key = (offer, binding['portal'])
            latest[key] = item
            if item['state'] == 'ack_completed':
                completed[key] = item
    return latest, completed


BusinessNeed = namedtuple('BusinessNeed', 'category action')


def business_need(active, state, source_changed=False):
    """Pure business need (new/update/withdraw/None) and action, before any presentation override."""
    published = bool(state and state['is_published'])
    action = 'add' if active else 'delete'
    category = ('update' if published else 'new') if active else 'withdraw' if published else None
    if active and published and not (source_changed or state['needs_update']):
        category = None
    return BusinessNeed(category, action)


def _classify(active, state, latest, changed=False, issue=None):
    category, action = business_need(active, state, changed)
    if issue or state and state.get('last_error') or latest and latest['state'] != 'ack_completed':
        category = 'error'
    return category, action


def _attempt_public(item, domain):
    if item is None:
        return None
    return {'attempt_id': item['attempt_id'], 'domain': domain, 'state': item['state'],
            'can_ack': item['state'] in {'transport_confirmed', 'ack_failed'}}


def _task(domain, subject, offer_ids, title, portal, action, category, state, latest, issue):
    unresolved = latest is not None and latest['state'] in UNRESOLVED
    if state and state.get('last_error') and not (latest and latest['state'] in ({'transport_failed'} | attempts.RESOLVED_STATES)):
        issue = issue or 'legacy_result_requires_reconciliation'
    if unresolved:
        subject = latest['binding'].get('subject', subject)
        offer_ids = latest['binding'].get('members', offer_ids)
        action = latest['binding']['action']
        issue = 'attempt_unresolved'
    return {'key': f"{domain}:{subject['kind']}:{subject['id']}:{portal}:{action}",
            'domain': domain, 'subject': subject, 'offer_ids': sorted(offer_ids),
            'title': str(title or '')[:200], 'portal': portal, 'action': action,
            'category': category, 'operation': 'reconcile' if unresolved else
                'withdraw' if action == 'delete' else 'update' if state and state['is_published'] else 'publish',
            'published': bool(state and state['is_published']), 'issue': issue,
            'transport_state': latest['state'] if latest else 'legacy_error' if state and state.get('last_error') else 'published' if state and state['is_published'] else 'none',
            'last_result': _attempt_public(latest, domain), 'package': None,
            'send_allowed': False}


def _source_changed(root, item):
    # Compare current business inputs with the exact captured context, without
    # consulting a dictionary cache or downloading public data during listing.
    # Legacy whole-record digests measure package freshness, not publication
    # changes. CRM writes record portal-specific business changes independently.
    if item['generation_context'].get('input_projection') != 2:
        return False
    from .domestic_export_inputs import ProjectionUnavailable
    try:
        return domestic._state(root, item['offer_id'], item['generation_context'],
                               file_reader=catalog._input_reader(), max_entries=catalog.MAX_INPUT_ENTRIES)[0] != item['input_fingerprint']
    except ProjectionUnavailable:
        # Dictionary availability limits package verification, not CRM status.
        # Writes through CRM track business changes independently of this cache.
        return False


def _domestic_on(conn, root, base, offer_id, history, *, package=True, needs_out=None):
    """Domestic classification on an open connection. package=False skips pointer/presentation
    (qualification needs the business result only). Output is unchanged for package=True."""
    result = []
    # Optional bounded selection shares the exact same classifier as the queue.
    if offer_id is not None and (type(offer_id) is not int or not 0 < offer_id <= 2**63-1):
        raise ValueError('Invalid domestic offer')
    where = '' if offer_id is None else f' WHERE ID={offer_id}'
    offers = _rows(conn, 'SELECT ID,Status_oferty,Tytul,Typ_nieruchomosci FROM EstateData'+where+' ORDER BY CAST(ID AS INTEGER)')
    states = {(row['offer_id'], row['portal_key']): dict(row) for row in conn.execute('SELECT * FROM offer_portal_sync')} if _table(conn, 'offer_portal_sync') else {}
    if offer_id is not None:
        states = {key: value for key, value in states.items() if key[0] == offer_id}
    latest, completed = _by_pair(history)
    for offer in offers:
        limits.check('classify_offer')
        identifier = int(offer['ID'])
        active = str(offer['Status_oferty'] or '').strip().lower() == 'aktywna'
        try:
            revision = input_revision(conn, identifier) if _table(conn, 'offer_portal_sync_events') else 0
            source_issue = None
        except Exception:
            revision, source_issue = None, 'inputs_unstable'
        plot = sets.is_plot(offer['Typ_nieruchomosci'])
        portals = list(sets.BASE_PORTALS)
        # Keep earlier GG attempts visible, also after reclassification.
        guru = states.get((identifier, 'gruntguru'))
        if plot or guru and (guru['is_published'] or guru.get('last_error')) or (identifier, 'gruntguru') in latest:
            portals.append('gruntguru')
        for portal in portals:
            state = states.get((identifier, portal))
            last = latest.get((identifier, portal))
            baseline = completed.get((identifier, portal))
            issue = source_issue
            changed = False  # Revision protects attempts; it is not publication state.
            effective = active and (portal != 'gruntguru' or plot)
            if baseline is not None and state and state['is_published']:
                _, manifest, _ = catalog._metadata(base, baseline['binding']['package_id'])
                if manifest is None:
                    issue = 'publication_baseline_unavailable'
                else:
                    # A source change only matters for a publication that stays wanted (update); a withdrawal
                    # does not depend on it, and a reclassified GruntGuru plot cannot be re-validated as 'add'.
                    try: changed = changed or (effective and _source_changed(root, manifest))
                    except Exception: issue = 'inputs_unavailable'
            if _table(conn, 'offer_portal_sync_events') and attempts._legacy_pending(conn, identifier, portal):
                issue = 'legacy_unresolved'
            if needs_out is not None:
                needs_out[(identifier, portal)] = business_need(effective, state, changed)
            category, action = _classify(effective, state, last, changed, issue)
            if category is None:
                continue
            task = _task('domestic', {'kind': 'offer', 'id': identifier}, [identifier], offer['Tytul'],
                         portal, action, category, state, last, issue)
            if package:
                pointer = sets.current(base, identifier, task['action'])
                package_id = pointer['packages'].get(portal) if pointer else None
                if package_id:
                    presented = sets.presentation(base, package_id)
                    _, manifest, _ = catalog._metadata(base, package_id)
                    availability = presented['state']
                    if manifest is not None:
                        try:
                            if _source_changed(root, manifest): availability = 'STALE'
                        except Exception: availability = 'BLOCKED'
                    task['package'] = {key: presented[key] for key in ('package_id', 'prepared_at', 'checked_at')}
                    task['package']['state'] = availability
                task['send_allowed'] = not task['issue'] and task['package'] is not None and task['package']['state'] in {'READY', 'UNVERIFIED'}
            result.append(task)
    known = {int(row['ID']) for row in offers}
    for (identifier, portal), state in states.items():
        if identifier not in known and (state['is_published'] or state.get('last_error')):
            result.append(_task('domestic', {'kind': 'offer', 'id': identifier}, [identifier],
                'Brak danych źródłowych oferty', portal, 'delete', 'error', state,
                latest.get((identifier, portal)), 'source_offer_missing'))
    return result


@performance.measured('domestic_queue')
def _domestic(root, *, offer_id=None, ignore_prepared=False):
    path = root/'databases/IDB.db'
    if not path.is_file():
        raise ValueError('Domestic source database unavailable')
    _, base = catalog._root()
    with _read(path) as conn:
        return _domestic_on(conn, root, base, offer_id,
                            _history(conn, 'domestic', ignore_prepared=ignore_prepared, offer_id=offer_id))


def _foreign_subject(offer, portal, action):
    group = (action == 'add' and portal == 'tabelaofert'
             and offer['source_platform'] == 'cyprus_constructions' and offer['development_id'] is not None)
    return {'kind': 'cyprus_development' if group else 'foreign_offer',
            'id': offer['development_id'] if group else offer['id']}


def _foreign_qualifications(conn, *, ignore_prepared=False):
    """CRM-only task projection, before package enrichment; one SQLite snapshot."""
    from .foreign_consistency import revision as foreign_revision
    result = []
    needs = {}
    offers = _rows(conn, 'SELECT id,offer_title,is_active,source_platform,development_id FROM foreign_offers ORDER BY id')
    states = {(row['foreign_offer_id'], row['portal_key']): dict(row) for row in conn.execute('SELECT * FROM foreign_offer_portal_sync')} if _table(conn, 'foreign_offer_portal_sync') else {}
    history = (_history(conn, 'foreign', ignore_prepared=True) if ignore_prepared else _history(conn, 'foreign'))
    latest, completed = _by_pair(history)
    sold = {row[0] for row in conn.execute("SELECT foreign_offer_id FROM foreign_offer_export_warnings WHERE warning_code='source_sold_out' AND resolved_at IS NULL")} if _table(conn, 'foreign_offer_export_warnings') else set()
    try: revision, source_issue = foreign_revision(conn), None
    except Exception: revision, source_issue = None, 'foreign_revision_unavailable'
    # Agent mutations still advance the global package revision. Their precise
    # publication changes are recorded in portal flags, not inferred from it.
    from .foreign_consistency import EVENT
    last_business_event = (conn.execute('SELECT COALESCE(MAX(id),0) FROM foreign_offer_portal_sync_events '
                                        'WHERE event_type=?', (EVENT,)).fetchone()[0]
                           if _table(conn, 'foreign_offer_portal_sync_events') else 0)
    for offer in offers:
        identifier = offer['id']
        active = offer['is_active'] == 1 and identifier not in sold
        for portal in ('domiporta', 'tabelaofert'):
            state = states.get((identifier, portal))
            last = latest.get((identifier, portal))
            baseline = completed.get((identifier, portal))
            changed = (baseline is not None and revision != baseline['revision']
                       and last_business_event > baseline['event_id'])
            needs[(identifier, portal)] = business_need(active, state, changed)
            category, action = _classify(active, state, last, changed, source_issue)
            if category is None:
                continue
            subject = _foreign_subject(offer, portal, action)
            task = _task('foreign', subject, [identifier], offer['offer_title'], portal, action,
                         category, state, last, source_issue)
            result.append(task)
    known = {row['id'] for row in offers}
    orphans = []
    for (identifier, portal), state in states.items():
        if identifier not in known and (state['is_published'] or state.get('last_error')):
            task = _task('foreign', {'kind': 'foreign_offer', 'id': identifier}, [identifier],
                'Brak danych źródłowych oferty', portal, 'delete', 'error', state,
                latest.get((identifier, portal)), 'source_offer_missing')
            orphans.append(task)
    return result, {'offers': offers, 'sold': sold, 'states': states,
                    'latest': latest, 'completed': completed, 'history': history, 'orphans': orphans, 'needs': needs}


def _merge_foreign_task(result, task):
    if task['key'] in result:
        previous = result[task['key']]
        previous['offer_ids'] = sorted(set(previous['offer_ids']+task['offer_ids']))
        if task['category'] == 'error':
            previous.update(category='error', issue=task['issue'], last_result=task['last_result'])
            previous['send_allowed'] = previous['send_allowed'] and not task['issue']
        elif task['category'] == 'update' and previous['category'] == 'new':
            previous.update(category='update', operation='update')
        return False
    result[task['key']] = task
    return True


def _foreign_project_changes(conn, context):
    """Evidence only: completed bindings and existing assignment events.

    Raw revision events do not contain old/new project IDs. Never infer a move
    solely from a global revision change or absence of export history.
    """
    offers = {row['id']: row for row in context['offers']}
    changed, projects = set(), set()
    for identifier, offer in offers.items():
        state = context['states'].get((identifier, 'tabelaofert'))
        if not state or not state['is_published']:
            continue
        baseline = context['completed'].get((identifier, 'tabelaofert'))
        previous = baseline['binding']['subject'] if baseline and baseline['binding']['action'] == 'add' else None
        current = _foreign_subject(offer, 'tabelaofert', 'add')
        if previous and previous != current and 'cyprus_development' in (previous['kind'], current['kind']):
            changed.add(identifier)
            projects.update(subject['id'] for subject in (previous, current) if subject['kind'] == 'cyprus_development')
    if _table(conn, 'foreign_offer_portal_sync_events'):
        for event in conn.execute("""SELECT id,foreign_offer_id,payload_json FROM foreign_offer_portal_sync_events
                WHERE event_type='update_required' AND portal_key='tabelaofert' ORDER BY id"""):
            identifier = event['foreign_offer_id']
            offer = offers.get(identifier)
            state = context['states'].get((identifier, 'tabelaofert'))
            baseline = context['completed'].get((identifier, 'tabelaofert'))
            if (offer is None or offer['source_platform'] != 'cyprus_constructions'
                    or not state or not state['is_published']
                    or baseline and event['id'] <= baseline['event_id']):
                continue
            try:
                payload = json.loads(event['payload_json'])
                assignment = (isinstance(payload, dict)
                              and payload.get('reason') == 'foreign_offer_development_assignment')
            except (ValueError, TypeError):
                assignment = True  # unreadable evidence must not authorize a move
            if assignment:
                changed.add(identifier)
                if offer['development_id'] is not None:
                    projects.add(offer['development_id'])
                if baseline and baseline['binding']['subject']['kind'] == 'cyprus_development':
                    projects.add(baseline['binding']['subject']['id'])
    return changed, projects


def _foreign_units_on(conn, *, ignore_prepared=False, needs_out=None):
    """Foreign unit plan on an open connection (one SQLite snapshot).

    ignore_prepared=True drops attempts that never started, giving the pure business-need view
    used by START qualification. Output for ignore_prepared=False is unchanged.
    """
    from .foreign_packages import _selection
    if not _table(conn, 'foreign_offers'):
        return []
    tasks, context = _foreign_qualifications(conn, ignore_prepared=ignore_prepared)
    merged = {}
    for task in tasks:
        _merge_foreign_task(merged, task)
    for task in context['orphans']:
        merged[task['key']] = task
    projects = {row['id']: row for row in _rows(conn, 'SELECT id,source_platform FROM foreign_developments ORDER BY id')} if _table(conn, 'foreign_developments') else {}
    changed, affected_projects = _foreign_project_changes(conn, context)
    pending = {}
    for item in context['history']:
        if item['state'] in UNRESOLVED:
            pending.setdefault(item['binding']['portal'], []).append(item)
    memberships = {}
    for offer in context['offers']:
        if offer['is_active'] == 1 and offer['id'] not in context['sold']:
            memberships.setdefault(offer['development_id'], []).append(offer['id'])
    units = []
    for task in merged.values():
        subject, portal, action = task['subject'], task['portal'], task['action']
        issues = [task['issue']] if task['issue'] else []
        try:
            _selection(subject['kind'], subject['id'], portal, action)
        except domestic.PreparationError:
            issues.append('unsupported_selection')
        members = [subject['id']]
        if subject['kind'] == 'cyprus_development':
            members = memberships.get(subject['id'], [])
            project = projects.get(subject['id'])
            if project is None or project['source_platform'] != 'cyprus_constructions':
                issues.append('project_unavailable')
            if not members:
                issues.append('no_eligible_project_members')
        if (portal == 'tabelaofert' and action == 'add'
                and (subject['kind'] == 'cyprus_development' and subject['id'] in affected_projects
                     or any(identifier in changed for identifier in members))):
            issues.append('project_assignment_requires_intervention')
        # Reuse the transport lifecycle's overlap rule, including older
        # unresolved attempts hidden by a newer record in the queue view.
        token = attempts._domain.set('foreign')
        try:
            selection = {'portal': portal, 'subject': subject, 'members': members}
            if any(attempts._same(item['binding'], selection) for item in pending.get(portal, ())):
                issues.append('attempt_unresolved')
        finally:
            attempts._domain.reset(token)
        if task['category'] == 'error' and not issues:
            issues.append(task['transport_state'])
        if needs_out is not None:
            needs_out[(subject['kind'], subject['id'], portal, action)] = _aggregate_need(context['needs'], task['offer_ids'], portal)
        units.append({'key': (subject['kind'], subject['id'], portal, action),
                      'subject': dict(subject), 'portal': portal, 'action': action,
                      'category': task['category'], 'operation': task['operation'],
                      'trigger_offer_ids': list(task['offer_ids']), 'members': list(members),
                      'issues': sorted(set(issues)), 'validation_required': True,
                      'preparation_allowed': task['category'] in {'new', 'update', 'withdraw'} and not issues})
    return units


def qualify_foreign_units(root):
    """Internal read-only preparation plan, NOT generation/send authorization.

    root is a trusted DATA_DIR Path. One SQLite read snapshot; no artifact root,
    directory scans, manifest/ZIP/XML reads, media fetches, new locks or writes.
    members is the full current eligible CRM membership, whereas
    trigger_offer_ids identifies the offers represented by queue qualification.
    Complete input/business validation remains the existing generator's job.
    """
    path = root/'databases/foreign_offers.db'
    if not path.is_file():
        return []
    with _read(path) as conn:
        return _foreign_units_on(conn)


def _aggregate_need(needs, offer_ids, portal):
    """Pure business need of a merged unit: update beats new beats withdraw."""
    found = [needs[(identifier, portal)].category for identifier in offer_ids if (identifier, portal) in needs]
    for category in ('update', 'new', 'withdraw'):
        if category in found:
            return BusinessNeed(category, 'delete' if category == 'withdraw' else 'add')
    return BusinessNeed(None, None)


Qualification = namedtuple('Qualification', 'required category action need members trigger_offer_ids issues blocking')
RESOLVED_FAILURE = 'transport_failed'   # confirmed not-sent failure: a conscious retry is allowed


def qualify_unit(conn, root, unit):
    """Business qualification of ONE unit on the caller's transaction connection.

    unit = {'domain','subject':{'kind','id'},'portal','action'}. Uses the shared queue rules
    on a history without never-started (prepared) attempts, so the unit's own prepared attempt
    neither creates nor hides a need. Other unresolved attempts stay blocking issues.
    Never grants transport; the permission is the committed START.
    """
    previous = conn.row_factory
    conn.row_factory = sqlite3.Row
    try:
        if unit['domain'] == 'domestic':
            return _qualify_domestic(conn, root, unit['subject']['id'], unit['portal'])
        return _qualify_foreign(conn, unit['subject'], unit['portal'], unit['action'])
    finally:
        conn.row_factory = previous


def qualify_unit_snapshot(unit):
    """Read-only qualification for the worker's pre-preparation check (no write transaction).

    Takes the same locks as list_tasks (dictionary lock + non-blocking input lock, so a busy lock
    raises LockBusy) and one read snapshot of the unit's domain database.
    """
    root = _source_root()
    path = root/'databases'/('foreign_offers.db' if unit['domain'] == 'foreign' else 'IDB.db')
    if not path.is_file():
        raise ValueError('Source database unavailable')
    with sets.locked():
        with _read(path) as conn:
            return qualify_unit(conn, root, unit)


def _qualification(need, task_category, members, triggers, issues):
    blocking = [item for item in issues if item != RESOLVED_FAILURE]
    return Qualification(need.category is not None, task_category, need.action, need.category,
                         list(members), list(triggers), list(issues), blocking)


def _qualify_domestic(conn, root, offer_id, portal):
    needs = {}
    # Domestic attempts are anchored on the offer itself, so this unit only needs that offer's history.
    history = _history(conn, 'domestic', ignore_prepared=True, offer_id=offer_id)
    _, base = catalog._root()
    with storage.lookup_scope(base):
        tasks = _domestic_on(conn, root, base, offer_id, history, package=False, needs_out=needs)
    task = next((row for row in tasks if row['portal'] == portal and row['subject']['id'] == offer_id), None)
    need = needs.get((offer_id, portal), BusinessNeed(None, None))
    issues = [task['issue']] if task and task['issue'] else []
    return _qualification(need, task['category'] if task else None, [offer_id], [offer_id], issues)


def _qualify_foreign(conn, subject, portal, action):
    needs = {}
    units = _foreign_units_on(conn, ignore_prepared=True, needs_out=needs)
    key = (subject['kind'], subject['id'], portal, action)
    unit = next((row for row in units if row['key'] == key), None)
    if unit is None:
        return _qualification(BusinessNeed(None, None), None, [], [], [])
    return _qualification(needs.get(key, BusinessNeed(None, None)), unit['category'], unit['members'],
                          unit['trigger_offer_ids'], unit['issues'])


@performance.measured('foreign_queue')
def _foreign(root, settings):
    path = root/'databases/foreign_offers.db'
    if not path.is_file():
        return []
    from . import foreign_packages as foreign
    _, base = catalog._root('foreign')
    candidates = {}
    if base.exists():
        for count, folder in enumerate(base.iterdir(), 1):
            if count > catalog.MAX_SCAN:
                raise ValueError('Foreign package scan limit exceeded')
            if not catalog.ID.fullmatch(folder.name):
                continue
            diagnostic, item, _ = catalog._metadata(base, folder.name, 'foreign')
            item = item or diagnostic.get('manifest')  # retain identity of a corrupt current ZIP
            if item is None:
                raise ValueError('Unidentifiable foreign artifact')
            key = (item['subject']['kind'], item['subject']['id'], item['portal'], item['action'])
            rank = (catalog._date(item['prepared_at']), item['package_id'])
            if key not in candidates or rank > candidates[key][0]:
                candidates[key] = (rank, item)
    with _read(path) as conn:
        if not _table(conn, 'foreign_offers'):
            return []
        tasks, context = _foreign_qualifications(conn)
        result = {}
        for task in tasks:
            if not _merge_foreign_task(result, task):
                continue
            key = (task['subject']['kind'], task['subject']['id'], task['portal'], task['action'])
            item = candidates.get(key, (None, None))[1]
            if item is not None:
                with performance.stage('foreign_verification'):
                    checked = foreign.verify_package(item['package_id'], settings=settings)
                task['package'] = {key: item[key] for key in ('package_id', 'prepared_at')}
                task['package'].update(state=checked['state'], checked_at=checked['checked_at'])
                if task['subject']['kind'] == 'cyprus_development':
                    task['offer_ids'] = sorted(set(task['offer_ids']+item['members']))
            task['send_allowed'] = not task['issue'] and task['package'] is not None and task['package']['state'] == 'READY'
        for task in context['orphans']:
            result[task['key']] = task
    return list(result.values())


def _collect_tasks(root, settings):
    """Caller holds the existing lock; shared by both read projections."""
    rows = _domestic(root)+_foreign(root, settings)
    # Pending group attempts can appear through multiple members. Keep one task.
    merged = {}
    for row in rows:
        if row['key'] not in merged or row['category'] == 'error':
            merged[row['key']] = row
    return sorted(merged.values(), key=lambda row: (CATEGORIES.index(row['category']), row['key']))


def _source_root():
    root = storage_paths.data_dir()
    if root is None or not root.is_dir():
        raise ValueError('External InvestmentData required')
    return root.resolve()


source_root = _source_root


def _counts(rows):
    return {category: sum(row['category'] == category for row in rows) for category in CATEGORIES}


def list_tasks(*, offset=0, limit=50, settings=None):
    if type(offset) is not int or not 0 <= offset <= MAX_OFFERS*8 or type(limit) is not int or not 1 <= limit <= 100:
        raise ValueError('Invalid queue pagination')
    root = _source_root()
    with sets.locked():
        _, base = catalog._root()
        with storage.lookup_scope(base):
            rows = _collect_tasks(root, settings)
    return {'queue_version': VERSION, 'ok': True, 'generated_at': datetime.now(timezone.utc).isoformat(),
            'items': rows[offset:offset+limit], 'total': len(rows), 'offset': offset, 'limit': limit,
            'counts': _counts(rows)}


def list_task_rows(*, max_rows, settings=None):
    """First ``max_rows`` queue rows from ONE collection (same snapshot/locking as list_tasks); for bounded scans."""
    if type(max_rows) is not int or not 1 <= max_rows <= 5000:
        raise ValueError('Invalid queue row limit')
    root = _source_root()
    with sets.locked():
        _, base = catalog._root()
        with storage.lookup_scope(base):
            rows = _collect_tasks(root, settings)
    return {'items': rows[:max_rows], 'total': len(rows)}


class ViewError(ValueError):
    def __init__(self, code):
        self.code = code
        super().__init__(code)


def _view_arguments(offset, limit, categories, portals, snapshot, domains=None, subject_kinds=None):
    domains = [] if domains is None else domains
    subject_kinds = [] if subject_kinds is None else subject_kinds
    if (type(offset) is not int or not 0 <= offset <= MAX_OFFERS*8
            or type(limit) is not int or not 1 <= limit <= 20
            or not isinstance(categories,list) or len(categories)>4
            or any(not isinstance(x,str) or x not in CATEGORIES for x in categories)
            or len(set(categories))!=len(categories)
            or not isinstance(portals,list) or len(portals)>5
            or any(not isinstance(x,str) or x not in domestic.PORTALS|{'otodom'} for x in portals)
            or len(set(portals))!=len(portals)
            or not isinstance(domains,list) or len(domains)>2
            or any(x not in {'domestic','foreign'} for x in domains) or len(set(domains))!=len(domains)
            or not isinstance(subject_kinds,list) or len(subject_kinds)>3
            or any(x not in {'offer','foreign_offer','cyprus_development'} for x in subject_kinds)
            or len(set(subject_kinds))!=len(subject_kinds)
            or snapshot is not None and (not isinstance(snapshot,str) or not catalog.SHA.fullmatch(snapshot))):
        raise ViewError('invalid_request')


def _crm(state):
    if state is None:
        return dict(present=False,valid=True,is_published=None,needs_update=None)
    valid = all(type(state[key]) is int and state[key] in (0,1) for key in ('is_published','needs_update'))
    return dict(present=True,valid=valid,is_published=state['is_published'] if valid else None,
                needs_update=state['needs_update'] if valid else None)


def _activity(domain, value):
    """Presentation of CRM data only; never a queue qualification rule."""
    if domain=='domestic':
        return {'aktywna':'active','nieaktywna':'inactive'}.get(str(value or '').strip().lower(),'unknown')
    if type(value) is int and value in (0,1):
        return 'active' if value==1 else 'inactive'
    return 'unknown'


def _view_context(root):
    offers, states, projects = {}, {}, {}
    for domain, filename, table, idcol, titlecol, sync, fk in (
        ('domestic','IDB.db','EstateData','ID','Tytul','offer_portal_sync','offer_id'),
        ('foreign','foreign_offers.db','foreign_offers','id','offer_title','foreign_offer_portal_sync','foreign_offer_id')):
        path = root/'databases'/filename
        if not path.is_file():
            continue
        with _read(path) as conn:
            if _table(conn,table):
                activitycol='Status_oferty' if domain=='domestic' else 'is_active'
                for row in _rows(conn,f'SELECT {idcol} AS id,{titlecol} AS title,{activitycol} AS activity FROM {table} ORDER BY {idcol}'):
                    offers[(domain,int(row['id']))] = dict(title=str(row['title'] or '')[:200],
                        activity=_activity(domain,row['activity']))
            if _table(conn,sync):
                rows = conn.execute(f'SELECT {fk},portal_key,is_published,needs_update FROM {sync} LIMIT ?', (MAX_OFFERS*8+1,)).fetchall()
                if len(rows)>MAX_OFFERS*8:raise ViewError('queue_unavailable')
                for row in rows:states[(domain,row[0],row[1])] = dict(row)
            if domain=='foreign' and _table(conn,'foreign_developments'):
                for row in _rows(conn,'SELECT id,name FROM foreign_developments ORDER BY id'):
                    projects[row['id']] = str(row['name'] or '')[:200]
    return offers, states, projects


def _offer_group(domain, identifier, offers):
    source=offers.get((domain,identifier),{})
    return dict(key=f'{domain}:offer:{identifier}',domain=domain,
        subject={'kind':'offer' if domain=='domestic' else 'foreign_offer','id':identifier},
        title=source.get('title',''),activity=source.get('activity','unknown'),source_exists=(domain,identifier) in offers,
        offer_ids=[identifier],crm={},tasks=[],project_refs=[],members=[])


def _group_tasks(rows, context):
    offers, states, projects = context
    groups = {}
    for task in rows:
        domain,subject,portal = task['domain'],task['subject'],task['portal']
        if subject['kind']=='cyprus_development':
            key=f"foreign:project:{subject['id']}"
            group=groups.setdefault(key,dict(key=key,domain='foreign',subject=dict(subject),
                title=projects.get(subject['id'],''),activity='unknown',source_exists=subject['id'] in projects,
                offer_ids=[],crm={},tasks=[],project_refs=[],members=[]))
            group['tasks'].append(task)
            group['offer_ids']=sorted(set(group['offer_ids']+task['offer_ids']))
            for identifier in task['offer_ids']:
                owner=groups.setdefault(f'foreign:offer:{identifier}',_offer_group('foreign',identifier,offers))
                owner['crm'][portal]=_crm(states.get(('foreign',identifier,portal)))
                owner['project_refs'].append(dict(key=task['key'],project_key=key,portal=portal,
                    category=task['category'],operation=task['operation'],
                    package_state=task['package']['state'] if task['package'] else None,
                    transport_state=task['transport_state']))
        else:
            identifier=subject['id']
            group=groups.setdefault(f'{domain}:offer:{identifier}',_offer_group(domain,identifier,offers))
            group['tasks'].append(task)
            group['crm'][portal]=_crm(states.get((domain,identifier,portal)))
    for group in groups.values():
        if group['subject']['kind']=='cyprus_development':
            group['members']=[dict(offer_id=i,title=offers.get(('foreign',i),{}).get('title',''),
                activity=offers.get(('foreign',i),{}).get('activity','unknown'),
                source_exists=('foreign',i) in offers,crm=_crm(states.get(('foreign',i,'tabelaofert')))) for i in group['offer_ids']]
    return sorted(groups.values(),key=lambda g:(g['domain'],g['subject']['kind']=='cyprus_development',g['subject']['id']))


def _stable(value):
    if isinstance(value,dict):
        return {key:_stable(item) for key,item in value.items() if key not in {'checked_at','generated_at','page_offset'}}
    if isinstance(value,list):return [_stable(item) for item in value]
    return value


def list_offers(*, offset=0, limit=20, categories=None, portals=None, snapshot=None, settings=None,
                domains=None, subject_kinds=None, all_items=False):
    categories=[] if categories is None else categories
    portals=[] if portals is None else portals
    domains=[] if domains is None else domains
    subject_kinds=[] if subject_kinds is None else subject_kinds
    _view_arguments(offset,limit,categories,portals,snapshot,domains,subject_kinds)
    if type(all_items) is not bool or all_items and offset != 0:
        raise ViewError('invalid_request')
    root=_source_root()
    with sets.locked():
        _, base = catalog._root()
        with storage.lookup_scope(base):
            rows=_collect_tasks(root,settings)
            groups=_group_tasks(rows,_view_context(root))
    token=hashlib.sha256(json.dumps(_stable(groups),sort_keys=True,ensure_ascii=True,separators=(',',':')).encode()).hexdigest()
    if snapshot is not None and token!=snapshot:raise ViewError('snapshot_changed')
    positions={g['key']:(i//limit)*limit for i,g in enumerate(groups)}
    for group in groups:
        for ref in group['project_refs']:ref['page_offset']=positions[ref['project_key']]
        for member in group['members']:member['page_offset']=positions[f"foreign:offer:{member['offer_id']}"]
    def matches(group):
        return ((not domains or group['domain'] in domains)
                and (not subject_kinds or group['subject']['kind'] in subject_kinds)
                and any((not categories or row['category'] in categories) and (not portals or row['portal'] in portals)
                   for row in group['tasks']+group['project_refs'])
                )
    filtered=[g for g in groups if matches(g)]
    reply=dict(view_version=1,ok=True,snapshot=token,generated_at=datetime.now(timezone.utc).isoformat(),
        offset=offset,limit=limit,categories=sorted(categories),portals=sorted(portals),
        total=len(filtered),total_all=len(groups),offer_count=sum(g['subject']['kind']!='cyprus_development' for g in groups),
        project_count=sum(g['subject']['kind']=='cyprus_development' for g in groups),
        counts=_counts(rows),items=filtered if all_items else filtered[offset:offset+limit])
    if len(json.dumps(reply,ensure_ascii=True).encode())>1024*1024:raise ViewError('response_limit')
    return reply
