"""Listing-only regression probes: disposable metadata, no SQL/network/ZIP reads."""
from contextlib import contextmanager
import hashlib
import json
import socket
import sqlite3
import threading

import pytest

from modules.core import storage_paths
from InvestmentManager.integrator import domestic_sets as sets
from InvestmentManager.integrator import domestic_storage as storage
from InvestmentManager.integrator import domestic_package_catalog as catalog
from InvestmentManager.integrator import input_consistency, domestic_batch_limits as limits


@pytest.fixture
def store(tmp_path, monkeypatch):
    root = tmp_path/'data'
    base = root/'exports/domestic'
    base.mkdir(parents=True)
    (root/'databases').mkdir()
    monkeypatch.setattr(storage_paths, 'data_dir', lambda: root)
    monkeypatch.setattr(storage_paths, 'idb_db_path', lambda: root/'databases/IDB.db')
    def forbidden(*args, **kwargs):
        raise AssertionError('Listing must not access SQL, network or ZIP contents')
    monkeypatch.setattr(socket.socket, 'connect', forbidden)
    monkeypatch.setattr(socket, 'create_connection', forbidden)
    monkeypatch.setattr(sqlite3, 'connect', forbidden)
    monkeypatch.setattr(catalog, '_zip_integrity', forbidden)
    original_open = catalog._open
    @contextmanager
    def metadata_only(path, parent):
        assert path.suffix != '.zip'
        with original_open(path, parent) as stream:
            yield stream
    monkeypatch.setattr(catalog, '_open', metadata_only)
    return base


def seed(base, offer_id, *, action='add', state='READY', generation=None):
    packages = {}
    for index, portal in enumerate(sets.BASE_PORTALS, 1):
        package_id = f'{offer_id*100+index+(50 if action == "delete" else 0):032x}'
        packages[portal] = package_id
        folder = base/str(offer_id)/action/portal/package_id
        folder.mkdir(parents=True)
        context = {'schema': 1, 'portal': portal, 'action': action,
                   'generator': {'engine_sha256': '0'*64, 'python': '3.13', 'jinja2': '3.1', 'pillow': '11.0'},
                   'website_base_url': 'https://example.invalid', 'company_settings': {},
                   'dictionaries': [{'url': url, 'status': 'unavailable_fallback'}
                                    for url in sets.dictionaries.URLS] if portal == 'domiporta' else []}
        item = {'schema_version': 1, 'package_id': package_id, 'offer_id': offer_id,
                'portal': portal, 'action': action, 'status': 'prepared',
                'prepared_at': '2026-11-04T00:00:00+00:00', 'zip_name': 'test.zip', 'zip_size': 3,
                'zip_sha256': '0'*64, 'input_fingerprint': '0'*64, 'generation_context': context}
        raw = json.dumps(item).encode()
        (folder/'manifest.json').write_bytes(raw)
        (folder/'test.zip').write_bytes(b'zip')
        if state != 'UNVERIFIED':
            result = {'state': state, 'checked_at': '2026-11-04T00:00:01+00:00',
                      'reasons': [], 'warnings': [], 'verification_required': False}
            (folder/sets.CHECK_FILE).write_text(json.dumps({'schema_version': 1,
                'package_id': package_id, 'manifest_sha256': hashlib.sha256(raw).hexdigest(), 'result': result}))
    pointer = {'schema_version': 1, 'offer_id': offer_id, 'action': action,
               'generation_id': generation or f'{offer_id*10+(action == "delete"):032x}',
               'packages': packages, 'prepared_at': '2026-11-04T00:00:00+00:00'}
    (base/str(offer_id)/action/'current.json').write_text(json.dumps(pointer))
    return pointer


def test_65_sets_one_scan_and_presentation_only_for_page(store, monkeypatch):
    for offer in range(1, 66):
        seed(store, offer)
    calls = {'scans': 0, 'presentations': 0}
    original_entries, original_row = storage.entries, sets._row
    def entries(base):
        calls['scans'] += 1
        yield from original_entries(base)
    def row(*args, **kwargs):
        calls['presentations'] += 1
        return original_row(*args, **kwargs)
    monkeypatch.setattr(storage, 'entries', entries)
    monkeypatch.setattr(sets, '_row', row)
    first = sets.list_sets(limit=50)
    assert first['total'] == 65 and [r['offer_id'] for r in first['items']] == list(range(65, 15, -1))
    assert calls == {'scans': 1, 'presentations': 50}
    assert all(r['state'] == 'READY' for r in first['items'])
    second = sets.list_sets(offset=50, limit=50)
    assert second['total'] == 65 and [r['offer_id'] for r in second['items']] == list(range(15, 0, -1))
    assert calls == {'scans': 2, 'presentations': 65}


def test_filters_total_sorting_and_empty_page(store):
    seed(store, 1, state='UNVERIFIED')
    seed(store, 2, state='STALE')
    seed(store, 3)
    seed(store, 3, action='delete', state='STALE')
    reply = sets.list_sets(state='STALE', offset=1, limit=1)
    assert reply['total'] == 2 and [(r['offer_id'], r['action']) for r in reply['items']] == [(2, 'add')]
    assert sets.list_sets(offer_id=3, action='delete')['total'] == 1
    assert sets.list_sets(state='UNVERIFIED')['items'][0]['offer_id'] == 1
    assert sets.list_sets(offset=4)['items'] == []
    assert sets.list_sets(offset=4)['total'] == 4


@pytest.mark.parametrize('problem', ['duplicate', 'manifest_binding', 'manifest_hash', 'linked_file', 'linked_parent'])
def test_index_preserves_fail_closed_validation(store, monkeypatch, problem):
    pointer = seed(store, 1)
    pid = pointer['packages']['no']
    folder = storage.structured(store, {'offer_id': 1, 'action': 'add', 'portal': 'no', 'package_id': pid})
    if problem == 'duplicate':
        (store/'2/add/no'/pid).mkdir(parents=True)
    elif problem in {'manifest_binding', 'manifest_hash'}:
        path = folder/'manifest.json'
        item = json.loads(path.read_text())
        item['offer_id' if problem == 'manifest_binding' else 'input_fingerprint'] = 2 if problem == 'manifest_binding' else '1'*64
        path.write_text(json.dumps(item))
    else:
        original = catalog._link
        unsafe = folder/'manifest.json' if problem == 'linked_file' else store/'1/add/no'
        monkeypatch.setattr(catalog, '_link', lambda path: path == unsafe or original(path))
    if problem == 'linked_parent':
        with pytest.raises(ValueError, match='Unsafe package path|Linked'):
            sets.list_sets()
    else:
        row = sets.list_sets()['items'][0]['items'][0]
        assert row['state'] == ('UNVERIFIED' if problem == 'manifest_hash' else 'INVALID')
        assert row['reasons'] and not row['transport_eligible']


def test_index_never_uses_partial_lookup_after_limit(store, monkeypatch):
    seed(store, 1)
    for number in range(15):
        (store/f'unknown-{number}').touch()
    monkeypatch.setattr(catalog, 'MAX_SCAN', 1)
    with pytest.raises(storage.LookupLimit):
        sets.list_sets()
    # Even an aborted listing releases both locks.
    with limits.scope(), sets.locked():
        pass


def test_location_index_is_not_reused_between_requests(store):
    seed(store, 1)
    assert sets.list_sets()['total'] == 1
    seed(store, 2)
    assert sets.list_sets()['total'] == 2


def test_listing_keeps_input_lock_and_consistent_pointer(store, monkeypatch):
    old = seed(store, 1)
    entered, attempted, rejected = threading.Event(), threading.Event(), []
    original = sets._row
    def competing_writer():
        assert entered.wait(5)
        try:
            with input_consistency.input_lock():
                rejected.append(False)
        except input_consistency.ConsistencyError:
            rejected.append(True)
        finally:
            attempted.set()
    thread = threading.Thread(target=competing_writer)
    thread.start()
    def row(*args, **kwargs):
        entered.set()
        assert attempted.wait(5)
        return original(*args, **kwargs)
    monkeypatch.setattr(sets, '_row', row)
    reply = sets.list_sets()
    thread.join(5)
    assert not thread.is_alive() and rejected == [True]
    assert reply['items'][0]['generation_id'] == old['generation_id']
    # A writer can replace the complete pointer after the listing releases it.
    with sets.locked():
        pointer = old | {'generation_id': 'f'*32}
        sets._atomic_json(store/'1/add/current.json', pointer, store)
    assert sets.list_sets()['items'][0]['generation_id'] == 'f'*32
