"""S4.4 characterization of the scheduler state primitives: SchedulerError, _json_object, _directory, _read, _write, runner_lock.

They are exercised through `InvestmentManager.scheduled_jobs` (the names the rest of the code and the tests use), so they must pass
unchanged before AND after the primitives move to `scheduler_state`. Disposable DATA_DIR only.
"""
import json
import os
import subprocess
import sys

import pytest

from InvestmentManager import scheduled_jobs as jobs
from modules.core import storage_paths

POSIX = os.name == 'posix'


@pytest.fixture
def root(tmp_path, monkeypatch):
    monkeypatch.setenv('DATA_DIR', str(tmp_path))
    return tmp_path


def _temporaries(root):
    return sorted(p.name for p in (root / 'scheduler').glob('.scheduler-*'))


# ------------------------------------------------------------------------------------------------ SchedulerError / _json_object

def test_scheduler_error_is_a_plain_exception_carrying_only_the_code():
    assert jobs.SchedulerError.__mro__[1] is Exception and jobs.SchedulerError.__module__ in {'InvestmentManager.scheduled_jobs', 'InvestmentManager.scheduler_state'}
    error = jobs.SchedulerError('invalid_config.json')
    assert str(error) == 'invalid_config.json' and error.args == ('invalid_config.json',)
    assert jobs.SchedulerError.__doc__.startswith('Safe, stable diagnostic code')


def test_json_object_rejects_duplicate_keys_and_keeps_the_first_order():
    assert jobs._json_object([('a', 1), ('b', 2)]) == {'a': 1, 'b': 2} and list(jobs._json_object([('b', 1), ('a', 2)])) == ['b', 'a']
    with pytest.raises(ValueError, match='Duplicate JSON key'):
        jobs._json_object([('a', 1), ('a', 2)])


# ------------------------------------------------------------------------------------------------ _directory

def test_directory_is_data_dir_scheduler_and_is_created_only_on_request(root):
    assert jobs._directory() == root / 'scheduler' and not (root / 'scheduler').exists()
    created = jobs._directory(create=True)
    assert created == root / 'scheduler' and created.is_dir()
    if POSIX:
        assert (created.stat().st_mode & 0o777) == 0o700
    assert jobs._directory(create=True) == created            # idempotent (exist_ok)


def test_directory_needs_an_external_data_dir(monkeypatch):
    monkeypatch.setattr(storage_paths, 'data_dir', lambda: None)
    with pytest.raises(jobs.SchedulerError, match='^external_data_dir_required$'):
        jobs._directory()


def test_directory_rejects_a_link_anywhere_in_the_private_path(root, tmp_path_factory):
    elsewhere = tmp_path_factory.mktemp('elsewhere')
    try:
        (root / 'scheduler').symlink_to(elsewhere, target_is_directory=True)
    except (OSError, NotImplementedError):
        pytest.skip('symbolic links are not available')
    for create in (False, True):
        with pytest.raises(jobs.SchedulerError, match='^unsafe_scheduler_path$'):
            jobs._directory(create=create)


# ------------------------------------------------------------------------------------------------ _read

def test_read_returns_the_default_for_a_missing_file_and_does_not_create_the_directory(root):
    assert jobs._read('state.json', {'d': 1}) == {'d': 1} and not (root / 'scheduler').exists()


def test_read_parses_valid_json(root):
    jobs._directory(create=True)
    (root / 'scheduler' / 'x.json').write_bytes('{"a": [1, 2], "b": "zażółć"}'.encode('utf-8'))
    assert jobs._read('x.json', None) == {'a': [1, 2], 'b': 'zażółć'}


@pytest.mark.parametrize('payload', [
    pytest.param(b'{', id='truncated'), pytest.param(b'', id='empty'), pytest.param(b'not json', id='text'),
    pytest.param(b'{"a": 1, "a": 2}', id='duplicate-key'), pytest.param(b'\xff\xfe\x00', id='bad-utf8'),
    pytest.param(b'[' * 60000, id='deep-nesting')])
def test_read_turns_every_malformed_file_into_a_coded_error_without_details(root, payload):
    jobs._directory(create=True)
    (root / 'scheduler' / 'bad.json').write_bytes(payload)
    with pytest.raises(jobs.SchedulerError) as error:
        jobs._read('bad.json', None)
    assert str(error.value) == 'invalid_bad.json' and error.value.__suppress_context__ is True


def test_read_size_limit_is_65536_bytes_inclusive(root):
    jobs._directory(create=True)
    ok = b'"' + b'a' * (65536 - 2) + b'"'
    assert len(ok) == 65536
    (root / 'scheduler' / 'big.json').write_bytes(ok)
    assert jobs._read('big.json', None) == 'a' * 65534
    (root / 'scheduler' / 'big.json').write_bytes(ok + b' ')
    with pytest.raises(jobs.SchedulerError, match='^invalid_big.json$'):
        jobs._read('big.json', None)


def test_read_refuses_something_that_is_not_a_regular_file(root):
    jobs._directory(create=True)
    (root / 'scheduler' / 'dir.json').mkdir()
    with pytest.raises((jobs.SchedulerError, OSError)) as error:        # POSIX: invalid_dir.json; Windows: PermissionError from open()
        jobs._read('dir.json', None)
    assert isinstance(error.value, jobs.SchedulerError) == POSIX or not POSIX


@pytest.mark.skipif(not POSIX, reason='O_NOFOLLOW semantics are POSIX-only')
def test_read_does_not_follow_a_symlinked_file(root, tmp_path_factory):
    jobs._directory(create=True)
    outside = tmp_path_factory.mktemp('outside') / 'secret.json'
    outside.write_text('{"leak": true}')
    (root / 'scheduler' / 'link.json').symlink_to(outside)
    with pytest.raises(OSError):
        jobs._read('link.json', None)


# ------------------------------------------------------------------------------------------------ _write

def test_write_creates_the_directory_and_the_exact_json_text(root):
    jobs._write('config.json', {'b': 1, 'a': ['ż', 2.5, None, True], 'c': {'z': 'x'}})
    raw = (root / 'scheduler' / 'config.json').read_bytes()
    assert raw == b'{"b": 1, "a": ["\\u017c", 2.5, null, true], "c": {"z": "x"}}'       # ensure_ascii, default separators, key order kept, no newline
    assert jobs._read('config.json', None) == {'b': 1, 'a': ['ż', 2.5, None, True], 'c': {'z': 'x'}}
    assert _temporaries(root) == []


def test_write_replaces_atomically_and_leaves_no_temporary_file(root):
    jobs._write('state.json', {'v': 1})
    jobs._write('state.json', {'v': 2})
    assert json.loads((root / 'scheduler' / 'state.json').read_text()) == {'v': 2} and _temporaries(root) == []


@pytest.mark.parametrize('value, error', [({'x': float('nan')}, ValueError), ({'x': object()}, TypeError)])
def test_write_failure_while_serializing_keeps_the_old_content_and_cleans_up(root, value, error):
    jobs._write('state.json', {'v': 1})
    before = (root / 'scheduler' / 'state.json').read_bytes()
    with pytest.raises(error):
        jobs._write('state.json', value)
    assert (root / 'scheduler' / 'state.json').read_bytes() == before and _temporaries(root) == []


def test_write_failure_of_the_final_replace_keeps_the_old_content_and_cleans_up(root, monkeypatch):
    jobs._write('state.json', {'v': 1})
    before = (root / 'scheduler' / 'state.json').read_bytes()

    def fail(*args):
        raise OSError('replace failed')

    monkeypatch.setattr(jobs.os, 'replace', fail)
    with pytest.raises(OSError, match='replace failed'):
        jobs._write('state.json', {'v': 2})
    assert (root / 'scheduler' / 'state.json').read_bytes() == before and _temporaries(root) == []


def test_write_fsyncs_the_file_before_the_replace(root, monkeypatch):
    order = []
    real_fsync, real_replace = os.fsync, os.replace
    monkeypatch.setattr(jobs.os, 'fsync', lambda fd: (order.append('fsync'), real_fsync(fd))[1])
    monkeypatch.setattr(jobs.os, 'replace', lambda a, b: (order.append('replace'), real_replace(a, b))[1])
    jobs._write('state.json', {'v': 1})
    assert order[0] == 'fsync' and order.index('replace') > order.index('fsync')
    if POSIX:
        assert order[-1] == 'fsync'                       # directory fsync after the replace


@pytest.mark.skipif(not POSIX, reason='symbolic links are reliably available on POSIX')
def test_write_refuses_a_symlinked_target(root, tmp_path_factory):
    jobs._directory(create=True)
    outside = tmp_path_factory.mktemp('outside') / 'target.json'
    outside.write_text('untouched')
    (root / 'scheduler' / 'state.json').symlink_to(outside)
    with pytest.raises(jobs.SchedulerError, match='^unsafe_scheduler_path$'):
        jobs._write('state.json', {'v': 1})
    assert outside.read_text() == 'untouched' and _temporaries(root) == []


def test_write_uses_a_private_temporary_name_in_the_same_directory(root, monkeypatch):
    seen = []
    real = os.replace
    monkeypatch.setattr(jobs.os, 'replace', lambda a, b: (seen.append((os.path.basename(a), os.path.dirname(a), str(b))), real(a, b))[1])
    jobs._write('state.json', {'v': 1})
    name, folder, target = seen[0]
    assert name.startswith('.scheduler-') and folder == str(root / 'scheduler') and target == str(root / 'scheduler' / 'state.json')


# ------------------------------------------------------------------------------------------------ runner_lock

def test_runner_lock_creates_runner_lock_in_the_scheduler_directory_and_is_not_reentrant(root):
    with jobs.runner_lock() as first:
        assert first is True and (root / 'scheduler' / 'runner.lock').is_file()
        with jobs.runner_lock() as second:                # a second open file description in the same process must not get the lock
            assert second is False
    with jobs.runner_lock() as again:                     # released on exit
        assert again is True
    if POSIX:
        assert ((root / 'scheduler' / 'runner.lock').stat().st_mode & 0o777) == 0o600


def test_runner_lock_is_released_when_the_body_raises(root):
    with pytest.raises(RuntimeError):
        with jobs.runner_lock() as acquired:
            assert acquired
            raise RuntimeError('boom')
    with jobs.runner_lock() as acquired:
        assert acquired is True


_CHILD = ('import os, sys\n'
          'from InvestmentManager import scheduled_jobs as j\n'
          'with j.runner_lock() as acquired:\n'
          '    print("acquired" if acquired else "busy", flush=True)\n'
          '    if len(sys.argv) > 1:\n'
          '        sys.stdin.readline()\n')


def test_runner_lock_excludes_another_process_and_is_released_by_its_end(root):
    with jobs.runner_lock() as acquired:
        assert acquired
        child = subprocess.run([sys.executable, '-c', _CHILD], capture_output=True, text=True, env=os.environ.copy(), timeout=30)
        assert child.returncode == 0, child.stderr
        assert child.stdout.strip() == 'busy'
    child = subprocess.run([sys.executable, '-c', _CHILD], capture_output=True, text=True, env=os.environ.copy(), timeout=30)
    assert child.returncode == 0 and child.stdout.strip() == 'acquired'


def test_runner_lock_held_by_a_child_blocks_this_process_until_the_child_exits(root):
    child = subprocess.Popen([sys.executable, '-c', _CHILD, 'hold'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, env=os.environ.copy())
    try:
        assert child.stdout.readline().strip() == 'acquired'
        with jobs.runner_lock() as acquired:
            assert acquired is False
    finally:
        child.communicate('\n', timeout=30)
    with jobs.runner_lock() as acquired:
        assert acquired is True


def test_runner_lock_refuses_a_link_in_the_private_path(root, tmp_path_factory):
    elsewhere = tmp_path_factory.mktemp('elsewhere')
    try:
        (root / 'scheduler').symlink_to(elsewhere, target_is_directory=True)
    except (OSError, NotImplementedError):
        pytest.skip('symbolic links are not available')
    with pytest.raises(jobs.SchedulerError, match='^unsafe_scheduler_path$'):
        with jobs.runner_lock():
            pass


@pytest.mark.skipif(not POSIX, reason='O_NOFOLLOW semantics are POSIX-only')
def test_runner_lock_does_not_follow_a_symlinked_lock_file(root, tmp_path_factory):
    jobs._directory(create=True)
    outside = tmp_path_factory.mktemp('outside') / 'lock'
    outside.write_text('x')
    (root / 'scheduler' / 'runner.lock').symlink_to(outside)
    with pytest.raises((jobs.SchedulerError, OSError)):
        with jobs.runner_lock():
            pass


# ------------------------------------------------------------------------------------------------ users of the primitives keep working

def test_scheduler_users_see_a_patched_write_through_their_own_module_namespace(root, monkeypatch):
    """`monkeypatch.setattr(jobs, '_write', ...)` must keep affecting the callers inside scheduled_jobs (existing tests rely on it)."""
    calls = []
    monkeypatch.setattr(jobs, '_write', lambda name, value: calls.append(name))
    jobs.configure({'version': 1, 'resize_images': {'enabled': True, 'interval_minutes': 5}}, now=100)
    assert 'config.json' in calls
