"""Structural move keeps the engine isolated and the existing CRM intact."""
import importlib.util
from pathlib import Path
import subprocess
import sys


def test_single_internal_package_and_no_top_level_copy():
    from InvestmentManager import export_engine
    root = Path(__file__).resolve().parents[2]
    assert Path(export_engine.__file__).resolve().parent == root/'InvestmentManager/export_engine'
    assert not (root/'export_engine').exists()
    assert importlib.util.find_spec('export_engine') is None


def test_dictionary_fallback_roots_are_preserved_after_move():
    from InvestmentManager.export_engine.portals.no.dictionaries import _candidate_paths
    root = Path(__file__).resolve().parents[2]
    paths = _candidate_paths()
    assert paths == [
        root/'InvestmentManager/export_engine/portals/no/noeDictionary_v_2_0.xml',
        root/'noeDictionary_v_2_0.xml',
        root.parent/'noeDictionary_v_2_0.xml',
    ]
    assert paths[0].is_file()


def test_existing_blueprint_identity_resources_and_hooks_are_unchanged(app):
    from InvestmentManager import investmentmanager_bp, require_crm_session, add_no_cache_headers
    root = Path(__file__).resolve().parents[2]
    assert app.blueprints['investmentmanager'] is investmentmanager_bp
    assert investmentmanager_bp.import_name == 'InvestmentManager'
    assert Path(investmentmanager_bp.root_path) == root/'InvestmentManager'
    assert require_crm_session in app.before_request_funcs['investmentmanager']
    assert add_no_cache_headers in app.after_request_funcs['investmentmanager']
    assert investmentmanager_bp.url_prefix == '/crm'


def test_internal_module_cli_still_requires_explicit_arguments():
    root = Path(__file__).resolve().parents[2]
    result = subprocess.run([sys.executable, '-B', '-m', 'InvestmentManager.export_engine', '--help'],
                            cwd=root, capture_output=True, text=True)
    assert result.returncode == 0, result.stderr
    assert '--data-dir' in result.stdout and '--output-dir' in result.stdout
