"""Approved INV-01B limits: fake clocks/network and disposable SQLite only."""
import sqlite3
import threading
import types
from urllib.error import URLError

import pytest

from tests.investmentmanager.test_domestic_batch import country, pointer
from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql, login
from InvestmentManager.integrator import domestic_batch as batch, domestic_batch_limits as limits
from InvestmentManager.integrator import domestic_sets as sets, domestic_packages as prep
from InvestmentManager.integrator import domestic_dictionaries as dictionaries
from InvestmentManager.integrator.domestic_dictionaries import _download as real_download


class Clock:
    value = 0.0
    def __call__(self):return self.value


@pytest.fixture
def clock(monkeypatch):
    value = Clock()
    monkeypatch.setattr(limits, 'perf_counter', value)
    return value


def stop_row(result):
    return result['sets'][-1] if result['sets'] else result


def test_expired_qualification_does_not_start_dictionary_fetch(country, clock, monkeypatch):
    original = batch._qualification
    def qualify(*a, **k):
        result = original(*a, **k);clock.value = 31
        return result
    monkeypatch.setattr(batch, '_qualification', qualify)
    monkeypatch.setattr(dictionaries, '_download', lambda *a: pytest.fail('Network after deadline'))
    result = batch.process_offer(17)
    assert result['code'] == 'budget_exhausted' and pointer(country) is None
    assert limits.current() is None


@pytest.mark.parametrize('after_portal', ['no', 'gruntguru'])
def test_deadline_between_portals_or_before_activation_preserves_old_set(country, clock, monkeypatch, after_portal):
    sets.prepare_set(17, 'add')
    before = pointer(country)
    sql(country, "UPDATE EstateData SET Cena='999999'")
    original = prep.prepare_package
    calls = []
    with monkeypatch.context() as scoped:
        def prepare(*args, **kwargs):
            calls.append(args[1]);result = original(*args, **kwargs)
            if args[1] == after_portal:clock.value = 31
            return result
        scoped.setattr(prep, 'prepare_package', prepare)
        result = batch.process_offer(17)
    assert stop_row(result)['code'] == 'budget_exhausted'
    assert not stop_row(result)['prepared'] and pointer(country) == before
    assert calls == (['no'] if after_portal == 'no' else list(sets.PORTALS))
    assert not list((country/'exports/domestic').glob('.set-*'))
    # Each new request gets its own 30 seconds; no stale context or new worker.
    assert batch.process_offer(17)['sets'][0]['code'] == 'prepared_verified'
    assert limits.current() is None


@pytest.mark.parametrize('when', ['pointer', 'first_move'])
def test_commit_overrun_finishes_complete_pointer_and_reports_unverified_set(country, clock, monkeypatch, when):
    original = sets._atomic_json
    publish = prep._publish
    with monkeypatch.context() as scoped:
        def commit(path, *args, **kwargs):
            result = original(path, *args, **kwargs)
            if when == 'pointer' and path.name == 'current.json':clock.value = 31
            return result
        def move(source, destination):
            result = publish(source, destination)
            if when == 'first_move' and destination.parent.name == 'no':clock.value = 31
            return result
        scoped.setattr(sets, '_atomic_json', commit)
        scoped.setattr(prep, '_publish', move)
        result = batch.process_offer(17)
    row = stop_row(result)
    assert row['code'] == 'budget_exhausted' and row['prepared'] and not row['verified']
    before = pointer(country)
    assert len(before['packages']) == 4
    assert not list((country/'exports/domestic').rglob(sets.CHECK_FILE))
    assert batch.process_offer(17)['sets'][0]['code'] == 'verified'
    assert pointer(country) == before


@pytest.mark.parametrize('which', ['dictionary', 'generator'])
def test_busy_thread_lock_is_not_waited_for(country, which):
    lock = dictionaries._lock if which == 'dictionary' else prep.generate._generation_lock
    acquired, release = threading.Event(), threading.Event()
    def hold():
        with lock:
            acquired.set();release.wait(5)
    holder = threading.Thread(target=hold)
    holder.start()
    try:
        assert acquired.wait(1)
        result = batch.process_offer(17)
        assert stop_row(result)['code'] == 'lock_busy'
        assert pointer(country) is None
    finally:
        release.set();holder.join(2)
    assert not holder.is_alive() and limits.current() is None


def test_busy_input_file_lock_has_safe_result(country, monkeypatch):
    import os
    if os.name == 'nt':
        import msvcrt
        module, name = msvcrt, 'locking'
    else:
        import fcntl
        module, name = fcntl, 'flock'
    with monkeypatch.context() as scoped:
        def busy(*a, **k):raise BlockingIOError(13, 'PRIVATE_LOCK_PATH')
        scoped.setattr(module, name, busy)
        result = batch.process_offer(17)
    assert result['code'] == 'lock_busy' and 'PRIVATE_LOCK_PATH' not in str(result)
    assert pointer(country) is None


@pytest.mark.parametrize('name', ['IDB.db', 'agents.db'])
def test_database_over_64_mib_stops_before_generation(country, name, monkeypatch):
    assert limits.MAX_DATABASE == 64*1024*1024
    with (country/'databases'/name).open('r+b') as stream:
        stream.truncate(limits.MAX_DATABASE+1)
    monkeypatch.setattr(sets, 'prepare_set', lambda *a, **k: pytest.fail('Oversized database'))
    result = batch.process_offer(17)
    assert result['code'] == 'database_limit' and result['sets'] == []
    assert pointer(country) is None


def test_wal_logical_size_is_checked_not_only_main_file(tmp_path, monkeypatch):
    path = tmp_path/'wal.db'
    with sqlite3.connect(path) as conn:
        conn.execute('PRAGMA journal_mode=WAL')
        conn.execute('CREATE TABLE t (value BLOB)');conn.commit()
        conn.execute('PRAGMA wal_checkpoint(TRUNCATE)')
        initial = path.stat().st_size
        conn.execute('INSERT INTO t VALUES (zeroblob(20000))');conn.commit()
        assert path.stat().st_size == initial
        monkeypatch.setattr(limits, 'MAX_DATABASE', initial)
        with limits.scope(), pytest.raises(limits.BatchStop) as caught:
            limits.database(path, conn)
        assert caught.value.code == 'database_limit'


@pytest.mark.parametrize('cause', ['busy', 'size', 'budget'])
def test_sqlite_backup_checks_progress_without_retries(tmp_path, clock, cause):
    path = tmp_path/'source.db';path.write_bytes(b'')
    calls = []
    class Source:
        def execute(self, statement):
            return types.SimpleNamespace(fetchone=lambda: (4096 if 'page_size' in statement else 1,))
        def backup(self, target, *, pages, progress, sleep):
            calls.append(1);assert pages == 128 and sleep == 0
            if cause == 'budget':clock.value = 31
            progress(sqlite3.SQLITE_BUSY if cause == 'busy' else 0, 0,
                     limits.MAX_DATABASE//4096+1 if cause == 'size' else 1)
    with limits.scope(), pytest.raises(limits.BatchStop) as caught:
        limits.backup(Source(), object(), path)
    assert caught.value.code == {'busy':'lock_busy', 'size':'database_limit', 'budget':'budget_exhausted'}[cause]
    assert calls == [1]


@pytest.mark.parametrize('wrapped', [False, True])
def test_network_timeout_is_capped_and_not_cached_as_manual_failure(country, clock, monkeypatch, wrapped):
    calls = []
    class Opener:
        def open(self, request, *, timeout):
            calls.append(timeout)
            error = TimeoutError('PRIVATE_PASSWORD')
            raise URLError(error) if wrapped else error
    monkeypatch.setattr(dictionaries, 'build_opener', lambda *a: Opener())
    monkeypatch.setattr(dictionaries, '_download', real_download)
    result = batch.process_offer(17)
    assert result['code'] == 'network_timeout' and calls == [5.0]
    assert 'PRIVATE_PASSWORD' not in str(result) and not dictionaries._cache
    assert pointer(country) is None and limits.current() is None


def test_network_timeout_tracks_remaining_budget_and_body_reads(clock, monkeypatch):
    timeouts, reads = [], []
    chunks = [b'<d><item id="1"/></d>', b'']
    sock = types.SimpleNamespace(settimeout=lambda value: timeouts.append(('read', value)))
    class Response:
        status = 200
        fp = types.SimpleNamespace(raw=types.SimpleNamespace(_sock=sock))
        def __enter__(self):return self
        def __exit__(self, *a):pass
        def read(self, size):pytest.fail('Scoped HTTP reads must be bounded read1 calls')
        def read1(self, size):
            assert size <= 65536
            reads.append(1);clock.value += .5
            return chunks.pop(0)
    class Opener:
        def open(self, request, *, timeout):
            timeouts.append(('open', timeout));clock.value += .5
            return Response()
    monkeypatch.setattr(dictionaries, 'build_opener', lambda *a: Opener())
    with limits.scope():
        clock.value = 27.5
        assert real_download(dictionaries.URLS[0]).startswith(b'<d>')
    assert timeouts == [('open', 2.5), ('read', 2.0), ('read', 1.5)] and len(reads) == 2


def test_expired_open_does_not_start_read_or_parse(clock, monkeypatch):
    closed = []
    class Response:
        status = 200
        def __enter__(self):return self
        def __exit__(self, *a):closed.append(True)
        def read(self, size):pytest.fail('Body read after deadline')
    class Opener:
        def open(self, *a, **k):clock.value = 31;return Response()
    monkeypatch.setattr(dictionaries, 'build_opener', lambda *a: Opener())
    with limits.scope(), pytest.raises(limits.BatchStop) as caught:
        real_download(dictionaries.URLS[0])
    assert caught.value.code == 'budget_exhausted' and closed == [True]


def test_manual_preparation_ignores_scoped_database_threshold(country, client, monkeypatch):
    monkeypatch.setattr(limits, 'MAX_DATABASE', 1)
    login(client)
    result = client.post('/crm/offers/17/export-package', json={'action':'add'})
    assert result.status_code == 201 and result.get_json()['replaced']
    assert limits.current() is None


def test_generator_overrun_does_not_start_package_writes(country, clock, monkeypatch):
    original = prep.generate.generate_domestic
    calls = []
    def generate(*args, **kwargs):
        result = original(*args, **kwargs);calls.append(1);clock.value = 31
        return result
    monkeypatch.setattr(prep.generate, 'generate_domestic', generate)
    monkeypatch.setattr(prep, '_write', lambda *a, **k: pytest.fail('Artifact write after deadline'))
    result = batch.process_offer(17)
    assert stop_row(result)['code'] == 'budget_exhausted'
    assert stop_row(result)['stage'] == 'generated_portal'
    assert calls == [1] and pointer(country) is None


def test_one_budget_is_shared_by_add_and_delete_sets(country, clock, monkeypatch):
    from InvestmentManager.integrator.portal_sync_state import set_offer_portal_sync_state
    sql(country, "UPDATE EstateData SET Typ_nieruchomosci='dom'")
    set_offer_portal_sync_state(offer_id=17, portal_key='gruntguru', state='published')
    original = batch._process_set
    calls = []
    def process(root, base, offer_id, action, settings, **kwargs):
        calls.append(action)
        if action == 'delete':
            assert limits.current().remaining() == 10
            clock.value = 31
        result = original(root, base, offer_id, action, settings, **kwargs)
        if action == 'add':clock.value = 20
        return result
    monkeypatch.setattr(batch, '_process_set', process)
    result = batch.process_offer(17)
    assert calls == ['add', 'delete']
    assert result['sets'][0]['prepared'] and result['sets'][0]['verified']
    assert result['sets'][1]['code'] == 'budget_exhausted' and not result['sets'][1]['prepared']
    assert pointer(country) is not None and pointer(country, 'delete') is None


def test_sqlite_busy_is_reported_without_exposing_error(country, monkeypatch):
    from InvestmentManager.integrator import sync_tasks
    def busy(*args, **kwargs):
        error = sqlite3.OperationalError('PRIVATE_DB_PATH')
        error.sqlite_errorcode = sqlite3.SQLITE_BUSY
        raise error
    monkeypatch.setattr(sync_tasks, '_rows', busy)
    result = batch.process_offer(17)
    assert result['code'] == 'lock_busy' and 'PRIVATE_DB_PATH' not in str(result)


def test_expired_budget_has_safe_http_response_and_does_not_leak_context(country, client, monkeypatch):
    login(client)
    monkeypatch.setattr(limits, 'OFFER_SECONDS', 0)
    result = client.post('/crm/offers/export-packages/domestic-batch/17', json={})
    assert result.status_code == 200 and result.get_json()['code'] == 'budget_exhausted'
    assert limits.current() is None
    plan = client.post('/crm/offers/export-packages/domestic-batch/plan', json={})
    assert plan.status_code == 503 and limits.current() is None


def test_manual_dictionary_download_retains_15_seconds(monkeypatch):
    calls = []
    body = b'<d><item id="1"/></d>'
    class Response:
        status = 200
        def __enter__(self):return self
        def __exit__(self, *args):pass
        def read(self, size):calls.append(('read', size));return body
    class Opener:
        def open(self, request, *, timeout):calls.append(('timeout', timeout));return Response()
    monkeypatch.setattr(dictionaries, 'build_opener', lambda *a: Opener())
    assert real_download(dictionaries.URLS[0]) == body
    assert calls == [('timeout', 15), ('read', dictionaries.MAX_BYTES+1)]
