"""Request-local timings over synthetic inputs, without transport or telemetry."""
from contextlib import contextmanager
import builtins
import os
import sqlite3

import pytest

from tests.investmentmanager.test_domestic_batch import country
from tests.investmentmanager.test_domestic_packages import data_root, isolated
from InvestmentManager.integrator import domestic_batch as batch, domestic_batch_timing as timing
from InvestmentManager.integrator import domestic_batch_limits as limits, domestic_sets as sets


def test_nested_measurements_are_inclusive_and_context_is_reset(monkeypatch):
    ticks = iter([0, 1, 2, 3, 4, 5])
    monkeypatch.setattr(timing, 'perf_counter', lambda: next(ticks))
    with timing.capture() as record:
        with timing.stage('prepare_set', action='add'):
            with timing.stage('prepare_portal', portal='no', action='add'):
                pass
    assert record['total_ms'] == 5000
    assert record['completed']
    assert [(s['elapsed_ms'], s['parent_id']) for s in record['stages']] == [(3000, None), (1000, 0)]
    assert timing._active.get() is None
    with timing.stage('manual_path'):
        pass
    assert len(record['stages']) == 2


@pytest.mark.parametrize('error', [ValueError('synthetic'), limits.BatchStop('budget_exhausted', 'safe_stage')])
def test_exception_keeps_partial_measurement_and_original_exception(error):
    with timing.capture() as record:
        with pytest.raises(type(error)) as caught:
            with timing.stage('prepare_portal', portal='domiporta'):
                raise error
    assert caught.value is error
    assert not record['completed'] and not record['stages'][0]['completed']
    assert record['stages'][0]['elapsed_ms'] >= 0
    assert timing._active.get() is None


@pytest.mark.parametrize('bad_clock', ['exception', 'nan', 'backwards'])
def test_clock_failure_never_changes_business_result(monkeypatch, bad_clock):
    values = iter([10, 9, 8, 7])
    def clock():
        if bad_clock == 'exception':
            raise RuntimeError('broken instrumentation')
        return float('nan') if bad_clock == 'nan' else next(values)
    monkeypatch.setattr(timing, 'perf_counter', clock)
    monkeypatch.setattr(batch, '_process_offer', lambda *a, **k: {'offer_id': 17, 'code': 'no_action', 'sets': []})
    result = batch.process_offer(17)
    assert {k: v for k, v in result.items() if k != 'timings'} == {'offer_id': 17, 'code': 'no_action', 'sets': []}
    assert result['timings']['total_ms'] is None and not result['timings']['completed']
    assert limits.current() is None and timing._active.get() is None


def test_instrumentation_performs_no_io_and_bounds_its_response(monkeypatch):
    def forbidden(*args, **kwargs):
        raise AssertionError('Timing must not perform I/O')
    with monkeypatch.context() as scoped:
        for module, attribute in ((builtins, 'open'), (os, 'open'), (sqlite3, 'connect')):
            scoped.setattr(module, attribute, forbidden)
        with timing.capture() as record:
            for index in range(520):
                with timing.stage('qualification'):
                    pass
    assert len(record['stages']) == 512 and record['truncated'] and not record['completed']


@pytest.mark.parametrize('failed_read', range(6))
def test_failure_of_any_nested_clock_read_keeps_business_flow(monkeypatch, failed_read):
    reads = []
    def clock():
        index = len(reads)
        reads.append(index)
        if index == failed_read:
            raise RuntimeError('Synthetic timing failure')
        return index
    monkeypatch.setattr(timing, 'perf_counter', clock)
    outcomes = []
    with timing.capture() as record:
        with timing.stage('prepare_set'):
            with timing.stage('prepare_portal'):
                outcomes.append('prepared')
    assert outcomes == ['prepared'] and len(reads) == 6
    assert not record['completed'] and timing._active.get() is None


def test_real_batch_portal_timings_and_noop_have_no_extra_io(country, monkeypatch):
    result = batch.process_offer(17)
    assert result['sets'][0]['code'] == 'prepared_verified'
    record = result['timings']
    assert record['completed'] and record['total_ms'] > 0
    assert {'qualification', 'dictionaries', 'prepare_set', 'prepare_portal',
            'preactivation_check', 'activation', 'verify_new_set', 'verify_portal'} <= {s['name'] for s in record['stages']}
    assert {s['portal'] for s in record['stages'] if s['name'] == 'prepare_portal'} == set(sets.PORTALS)
    assert {s['portal'] for s in record['stages'] if s['name'] == 'verify_portal'} == set(sets.PORTALS)
    for stage in record['stages']:
        if stage['parent_id'] is not None:
            assert record['stages'][stage['parent_id']]['elapsed_ms'] >= stage['elapsed_ms']
    # Compare the same live no-op with/without recording: every existing read,
    # lock and write executes equally often. Capture itself never reads inputs.
    import sys
    def traced_run():
        calls = {}
        def profile(frame, event, arg):
            if event == 'call':
                file, name = frame.f_code.co_filename, frame.f_code.co_name
                if ('integrator' in file and 'domestic_batch_timing.py' not in file
                        and name in {'entries', 'folder', '_open', '_state', '_records', 'input_lock', '_read', '_atomic_json'}):
                    key = (file, name)
                    calls[key] = calls.get(key, 0) + 1
        previous = sys.getprofile()
        try:
            sys.setprofile(profile)
            reply = batch.process_offer(17)
        finally:
            sys.setprofile(previous)
        return reply, calls
    enabled, before = traced_run()
    assert enabled['sets'][0]['code'] == 'current'
    assert 'prepare_set' not in {s['name'] for s in enabled['timings']['stages']}
    assert 'existing_set_check' in {s['name'] for s in enabled['timings']['stages']}
    @contextmanager
    def disabled():
        yield {}
    monkeypatch.setattr(timing, 'capture', disabled)
    disabled_result, after = traced_run()
    assert {k: v for k, v in enabled.items() if k != 'timings'} == {k: v for k, v in disabled_result.items() if k != 'timings'}
    assert before == after
