"""One owner per query/cache, with compatible historical imports."""
import ast
import hashlib
import importlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys

import pytest

ROOT = Path(__file__).resolve().parents[2]
CONTRACT = json.loads(Path(__file__).with_name('catalog-stage4-contract.json').read_text(encoding='utf8'))
SHARED = {'get_agents', 'get_branches', 'get_branches_office_data'}
WEBSITE_ONLY = CONTRACT['website_only_functions']


@pytest.mark.parametrize('legacy_first', [False, True])
def test_import_orders_keep_identity_and_do_not_start_apps_or_runtime(legacy_first, tmp_path):
    script = '''
import importlib, json, os, sys
from pathlib import Path
root = Path(os.environ['DATA_DIR'])
assert not root.exists()
order = sys.argv[1] == 'True'
names = ['modules.investment.functions', 'InvestmentWebsite.services.catalog', 'modules.core.agent_queries']
for name in names if order else reversed(names): importlib.import_module(name)
old, catalog, queries = [importlib.import_module(n) for n in names]
contract = json.loads(sys.argv[2])
for name in contract['functions']:
    owner = queries if name in {'get_agents', 'get_branches', 'get_branches_office_data'} else catalog
    assert getattr(old, name) is getattr(owner, name), name
    assert getattr(owner, name).__module__ == owner.__name__, name
for name in contract['website_only_functions']:
    assert getattr(catalog, name).__module__ == catalog.__name__, name
    assert not hasattr(old, name), name
assert old.time is catalog.time
for a,b in [('modules.investment.record_schema','InvestmentWebsite.offers.record_schema'),
            ('modules.investment.constants','InvestmentWebsite.services.catalog_constants')]:
    first = importlib.import_module(a if order else b)
    second = importlib.import_module(b if order else a)
    assert first is second and sys.modules[a] is sys.modules[b]
assert not hasattr(old, '__getattr__')
assert set(n for n in vars(old) if not n.startswith('__')) == set(contract['exports'])
assert not root.exists()
for forbidden in ['modules.core.app_factory','InvestmentManager.export_handoff','InvestmentManager.scheduled_jobs']:
    assert forbidden not in sys.modules, forbidden
print('ok')
'''
    env = os.environ.copy()
    env['DATA_DIR'] = str(tmp_path / 'runtime')
    env['PYTHONPATH'] = os.pathsep.join(filter(None, (str(ROOT), env.get('PYTHONPATH'))))
    result = subprocess.run([sys.executable, '-B', '-c', script, str(legacy_first), json.dumps(CONTRACT)],
                            cwd=tmp_path, env=env, capture_output=True, text=True,
                            encoding='utf8', timeout=30)
    assert result.returncode == 0, result.stderr
    assert result.stdout.strip() == 'ok'


def test_function_bodies_sql_decorators_and_record_contracts_are_unchanged():
    def digest(node):
        # Preserve the Python 3.12 baseline representation of empty fields.
        options = {"show_empty": True} if sys.version_info >= (3, 13) else {}
        return hashlib.sha256(ast.dump(node, include_attributes=False, **options).encode('utf8')).hexdigest()

    functions = {}
    globals_ = {}
    for relative in ['InvestmentWebsite/services/catalog.py', 'modules/core/agent_queries.py']:
        for node in ast.parse((ROOT / relative).read_text(encoding='utf8')).body:
            if isinstance(node, ast.FunctionDef):
                assert node.name not in functions
                functions[node.name] = digest(node)
            elif isinstance(node, ast.Assign):
                for target in node.targets:
                    if isinstance(target, ast.Name):
                        globals_[target.id] = digest(node)
    assert functions == {**CONTRACT['functions'], **WEBSITE_ONLY}
    assert globals_ == CONTRACT['globals']
    for key, relative in [('schema', 'InvestmentWebsite/offers/record_schema.py'),
                          ('constants', 'InvestmentWebsite/services/catalog_constants.py')]:
        definitions = {}
        for node in ast.parse((ROOT / relative).read_text(encoding='utf8')).body:
            if isinstance(node, ast.ClassDef):
                definitions[node.name] = digest(node)
            elif isinstance(node, ast.Assign):
                for target in node.targets:
                    if isinstance(target, ast.Name):
                        definitions[target.id] = digest(node)
        assert definitions == CONTRACT[key]
    facade = ast.parse((ROOT / 'modules/investment/functions.py').read_text(encoding='utf8'))
    assert not any(isinstance(node, (ast.FunctionDef, ast.ClassDef)) for node in ast.walk(facade))


@pytest.mark.parametrize('name', sorted(SHARED))
def test_shared_sql_results_and_cache_clearing_from_both_namespaces(name, tmp_path, monkeypatch):
    from modules.core import agent_queries as queries
    from modules.investment import functions as legacy

    database = tmp_path / 'agents.db'
    with sqlite3.connect(database) as conn:
        conn.executescript('''
CREATE TABLE agents_v2 (id INTEGER, first_name TEXT, last_name TEXT, email TEXT, phone TEXT, license TEXT, is_active INTEGER);
INSERT INTO agents_v2 VALUES (100,'Reserved','','','','',1),(101,'Anna','Test','a@example.invalid','123','L',1),(102,'Inactive','','','','',0);
CREATE TABLE branches_v2 (id INTEGER, name TEXT, title TEXT, image_url TEXT, info1 TEXT, info2 TEXT, is_active INTEGER);
INSERT INTO branches_v2 VALUES (1,'Town','','','','',1),(2,'Hidden','','','','',0);
CREATE TABLE agent_branches_v2 (agent_id INTEGER, branch_id INTEGER);
INSERT INTO agent_branches_v2 VALUES (101,1),(101,2);
''')
    calls = []

    class Manager:
        def __init__(self, target):
            assert target == 'agents'

        def __enter__(self):
            calls.append('open')
            self.conn = sqlite3.connect(database)
            return self.conn

        def __exit__(self, *args):
            self.conn.close()

    monkeypatch.setattr(queries, 'DatabaseConnectionManager', Manager)
    a, b = getattr(legacy, name), getattr(queries, name)
    assert a is b
    expected = {'get_agents': [('Anna', 'Test', 'a@example.invalid', '123', 'L', 101)],
                'get_branches': [(101, 'Town')],
                'get_branches_office_data': {'Town': {'key': 'Town', 'title': 'Oddział Town', 'image': '', 'info1': '', 'info2': ''}}}[name]
    a.cache_clear()
    try:
        assert a() == expected
        assert b() == expected
        assert calls == ['open']
        assert a.cache_info() == b.cache_info()
        assert b.cache_info().hits == 1
        a.cache_clear()
        assert b.cache_info().currsize == 0
        assert b() == expected
        assert calls == ['open', 'open']
        b.cache_clear()
        assert a.cache_info().currsize == 0
    finally:
        a.cache_clear()


@pytest.mark.parametrize('seconds', [30, 120])
def test_legacy_clock_monkeypatch_and_ttl_contract(seconds, monkeypatch):
    from modules.investment import functions as legacy
    from InvestmentWebsite.services import catalog

    assert legacy.time is catalog.time
    assert legacy.ttl_cache is catalog.ttl_cache
    clock = [100.0]
    monkeypatch.setattr(legacy.time, 'monotonic', lambda: clock[0])
    calls = []

    @legacy.ttl_cache(ttl_seconds=seconds)
    def read():
        calls.append('read')
        return len(calls)

    assert read() == 1
    clock[0] += seconds - 1
    assert read() == 1
    assert read.cache_info().hits == 1
    clock[0] += 2
    assert read() == 2
    read.cache_clear()
    assert read.cache_info().currsize == 0


def test_real_consumers_and_facade_share_canonical_objects(app):
    from InvestmentManager.routes import agents, offer_catalog
    from InvestmentWebsite.blueprints.investment import investment
    from InvestmentWebsite.offers import investment_facade
    from InvestmentWebsite.services import catalog
    from modules.core import agent_queries
    from modules.investment import functions as legacy

    for name in SHARED:
        assert getattr(agents, name) is getattr(agent_queries, name) is getattr(legacy, name)
        assert getattr(investment, name) is getattr(agent_queries, name)
    assert offer_catalog.invalidate_offer_caches is catalog.invalidate_offer_caches is legacy.invalidate_offer_caches
    assert investment_facade.get_active_agents is catalog.get_active_agents
    assert importlib.import_module('modules.investment.record_schema') is importlib.import_module('InvestmentWebsite.offers.record_schema')
    assert importlib.import_module('modules.investment.constants') is importlib.import_module('InvestmentWebsite.services.catalog_constants')


def test_invalidation_reaches_the_same_offer_caches_from_both_namespaces(monkeypatch):
    from modules.investment import functions as legacy
    from InvestmentWebsite.services import catalog
    from modules.core import agent_queries

    names = ['count_images', 'get_estate_description', 'video_exists', 'get_image_path',
             'list_offer_image_filenames', 'get_normalized_filter_options', 'get_unique_filter_values',
             'get_catalog_price_bounds', 'get_catalog_area_bounds', 'get_active_agents',
             'get_estates_count_by_wojewodztwo']
    cleared = []
    for name in names:
        assert getattr(legacy, name) is getattr(catalog, name)
        monkeypatch.setattr(getattr(catalog, name), 'cache_clear', lambda name=name: cleared.append(name))
    for name in SHARED:
        monkeypatch.setattr(getattr(agent_queries, name), 'cache_clear', lambda: pytest.fail('Agent cache cleared by offer mutation'))
    legacy.invalidate_offer_caches()
    assert cleared == names
    cleared.clear()
    catalog.invalidate_offer_caches()
    assert cleared == names
