"""S4.4: the scheduler state primitives live in `InvestmentManager.scheduler_state`; `scheduled_jobs` keeps the historical names as the SAME objects,
and the export modules use the primitives without importing the cron executor."""
import ast
from pathlib import Path

import pytest

from InvestmentManager import scheduled_jobs, scheduler_state

ROOT = Path(__file__).resolve().parents[2]
EXPORT_MODULES = ('export_arm', 'export_automation', 'export_control', 'export_jobs', 'export_resolution', 'export_job_runner')


@pytest.mark.parametrize('name', ['SchedulerError', '_json_object', '_directory', '_read', '_write', 'runner_lock'])
def test_scheduled_jobs_exposes_the_historical_names_as_the_same_objects(name):
    assert getattr(scheduled_jobs, name) is getattr(scheduler_state, name)


@pytest.mark.parametrize('public, private', [('directory', '_directory'), ('read', '_read'), ('write', '_write'), ('json_object', '_json_object')])
def test_public_names_are_the_same_objects_as_the_historical_private_ones(public, private):
    assert getattr(scheduler_state, public) is getattr(scheduler_state, private) is getattr(scheduled_jobs, private)


def test_the_moved_code_keeps_its_names_and_the_exception_is_defined_once():
    assert scheduler_state.SchedulerError.__module__ == 'InvestmentManager.scheduler_state'
    assert [f.__name__ for f in (scheduler_state.directory, scheduler_state.read, scheduler_state.write)] == ['_directory', '_read', '_write']
    assert not any(isinstance(v, type) and v.__name__ == 'SchedulerError' and v is not scheduler_state.SchedulerError
                   for v in vars(scheduled_jobs).values())


def _imported(path):
    tree = ast.parse(path.read_text(encoding='utf-8-sig'))
    found = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            found.update(alias.name for alias in node.names)
        elif isinstance(node, ast.ImportFrom):
            base = node.module or ''
            found.add(base)
            found.update(f'{base}.{alias.name}'.strip('.') for alias in node.names)
    return found


@pytest.mark.parametrize('module', EXPORT_MODULES)
def test_export_modules_do_not_import_the_cron_executor(module):
    imported = _imported(ROOT / 'InvestmentManager' / 'integrator' / f'{module}.py')
    assert not any(name.endswith('scheduled_jobs') for name in imported), imported
    assert 'InvestmentManager.scheduler_state' in imported


def test_scheduler_state_imports_only_the_standard_library_and_storage_paths():
    imported = _imported(ROOT / 'InvestmentManager' / 'scheduler_state.py')
    project = {name for name in imported if name.split('.')[0] in {'InvestmentManager', 'InvestmentWebsite', 'integrations', 'tools', 'blueprints'}
               or name.startswith('modules')}
    assert project <= {'modules.core', 'modules.core.storage_paths'}, project
