"""Migration contracts: one canonical source module, including legacy imports."""
import json
import os
from pathlib import Path
import subprocess
import sys

import pytest


ROOT = Path(__file__).resolve().parents[2]
ALIASES = [
    ('modules.homelanzarote.homelanzarote_scraper', 'integrations.homelanzarote.scraper'),
    *[(f'modules.tripinvest.{name}', f'integrations.tripinvest.{name}') for name in (
        'config', 'helpers', 'listing_parser', 'listing_crawler', 'details_parser', 'details_crawler')],
    *[(f'modules.avarten.{name}', f'integrations.avarten.{name}') for name in (
        'rest_client', 'php_serialized', 'listing_crawler', 'details_crawler')],
    *[(f'modules.cyprus_constructions.{name}', f'integrations.cyprus_constructions.{name}') for name in (
        'live_client', 'cyprus_all_projects', 'cyprus_project_details')],
    ('modules.offers.connectors.tripinvest_connector', 'integrations.tripinvest.connector'),
    ('modules.offers.connectors.avarten_connector', 'integrations.avarten.connector'),
]


def run_python(arguments, tmp_path):
    env = os.environ.copy()
    env['PYTHONPATH'] = os.pathsep.join(filter(None, (str(ROOT), env.get('PYTHONPATH'))))
    env['PYTHONDONTWRITEBYTECODE'] = '1'
    return subprocess.run([sys.executable, '-B', *arguments], cwd=tmp_path, env=env,
                          capture_output=True, text=True, encoding='utf8', timeout=30)


@pytest.mark.parametrize('old,new', ALIASES)
@pytest.mark.parametrize('legacy_first', [False, True])
def test_legacy_import_is_the_same_module_from_another_cwd(old, new, legacy_first, tmp_path):
    code = '''
import importlib, json, sys
old, new, first = sys.argv[1:]
a = importlib.import_module(old if first == 'True' else new)
b = importlib.import_module(new if first == 'True' else old)
assert a is b
assert a.__name__ == new
assert sys.modules[old] is sys.modules[new]
marker = object()
a._migration_identity_marker = marker
assert b._migration_identity_marker is marker
assert not any(name in sys.modules for name in ('flask', 'InvestmentManager', 'modules.core.app_factory'))
print(json.dumps({'canonical': a.__name__, 'same': a is b}))
'''
    result = run_python(['-c', code, old, new, str(legacy_first)], tmp_path)
    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == {'canonical': new, 'same': True}


def test_cyprus_cache_and_monkeypatch_have_one_owner(monkeypatch):
    import importlib

    legacy = importlib.import_module('modules.cyprus_constructions.live_client')
    canonical = importlib.import_module('integrations.cyprus_constructions.live_client')
    monkeypatch.setenv('CYPRUS_CONSTRUCTIONS_CACHE_TTL', '900')
    monkeypatch.setattr(canonical, '_PAYLOAD_CACHE', {})
    calls = []

    def scrape(url):
        calls.append(url)
        return {'projects': [{'id': 'fixture-project'}]}

    monkeypatch.setattr(legacy.cyprus_all_projects, 'scrape_all_projects', scrape)
    assert legacy.fetch_projects('https://example.invalid/projects') == canonical.fetch_projects(
        'https://example.invalid/projects')
    assert calls == ['https://example.invalid/projects']
    assert legacy._PAYLOAD_CACHE is canonical._PAYLOAD_CACHE


@pytest.mark.parametrize('name', ['cyprus_all_projects', 'cyprus_project_details'])
def test_existing_cyprus_cli_help_survives_module_and_file_entrypoints(name, tmp_path):
    results = [
        run_python(['-m', f'{package}.{name}', '--help'], tmp_path)
        for package in ('modules.cyprus_constructions', 'integrations.cyprus_constructions')
    ]
    results += [
        run_python([str(ROOT / package / f'{name}.py'), '--help'], tmp_path)
        for package in ('modules/cyprus_constructions', 'integrations/cyprus_constructions')
    ]
    for result in results:
        assert result.returncode == 0, result.stderr
        assert '--output' in result.stdout and 'usage:' in result.stdout
    assert len({result.stdout for result in results}) == 1


def test_public_registry_uses_canonical_connectors():
    from integrations.avarten.connector import AvartenConnector
    from integrations.tripinvest.connector import TripinvestConnector
    from InvestmentWebsite.offers.registry import registry

    assert type(registry.get('avarten')) is AvartenConnector
    assert type(registry.get('tripinvest')) is TripinvestConnector
