import ast
import hashlib
import io
import sqlite3
import subprocess
import sys
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path

import pytest

from InvestmentManager.export_engine.generate import generate_domestic, generate_foreign, generate_cyprus, generate_withdrawal
from InvestmentManager.export_engine.runtime_paths import LocalInputs, read_connection, use, current


def contents(content):
    with zipfile.ZipFile(io.BytesIO(content)) as archive:
        result = {name: archive.read(name) for name in archive.namelist()}
    for name, body in result.items():
        if name.endswith('.xml'):
            ET.fromstring(body)
    return result


def snapshot(root):
    return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in root.rglob('*') if p.is_file()}


@pytest.mark.parametrize('portal', ['no', 'otodom', 'domiporta', 'tabelaofert', 'gruntguru'])
@pytest.mark.parametrize('action', ['add', 'delete'])
def test_domestic_builds_xml_and_zip_without_input_writes(data_root, portal, action):
    before = snapshot(data_root)
    name, content = generate_domestic(LocalInputs(data_root), portal, 17, action)
    files = contents(content)
    assert name.endswith('.zip') and any(n.endswith('.xml') for n in files)
    if action == 'add':
        assert 'image_17_url_0.jpg' in files and 'image_17_url_1.jpg' in files
        # Source algorithm watermarks every image except the last.
        assert files['image_17_url_0.jpg'] != (data_root/'offers/17/image_17_url_0.jpg').read_bytes()
        assert files['image_17_url_1.jpg'] == (data_root/'offers/17/image_17_url_1.jpg').read_bytes()
    else:
        assert not any(n.endswith('.jpg') for n in files)
    assert snapshot(data_root) == before


@pytest.mark.parametrize('portal', ['domiporta', 'tabelaofert'])
def test_foreign_single_preserves_identifiers_and_no_publication_writes(data_root, portal):
    before = snapshot(data_root)
    _, content, metadata = generate_foreign(LocalInputs(data_root), portal, 11)
    files = contents(content)
    assert metadata['advert_id'] == 'foreign_11' and metadata['uploaded'] is False
    assert b'foreign_11' in next(body for n, body in files.items() if n.endswith('.xml'))
    assert snapshot(data_root) == before


def test_cyprus_sold_out_skip_ids_images_and_read_only(data_root):
    before = snapshot(data_root)
    package = generate_cyprus(LocalInputs(data_root), 7)
    assert package['ready'] and package['sold_out_offer_ids'] == [12]
    assert [o['advert_id'] for o in package['offers']] == ['foreign_11', 'foreign_13']
    files = contents(package['zip_bytes'])
    assert set(files) == {'oferty.xml','image_foreign_11_url_0.jpg','image_foreign_13_url_0.jpg'}
    assert snapshot(data_root) == before


@pytest.mark.parametrize('portal', ['domiporta', 'tabelaofert'])
def test_sold_out_withdrawal_is_only_prepared_not_confirmed(data_root, portal):
    before = snapshot(data_root)
    package = generate_withdrawal(LocalInputs(data_root), portal, 12)
    assert package['ready'] and package['action'] == 'delete'
    xml = '\n'.join(body.decode() for n, body in contents(package['zip_bytes']).items() if n.endswith('.xml'))
    assert 'foreign_12' in xml
    assert ('AdvertsToDelete' in xml if portal == 'domiporta' else 'oferta_usun' in xml)
    assert snapshot(data_root) == before


@pytest.mark.parametrize('portal', ['domiporta', 'tabelaofert'])
def test_foreign_validation_still_rejects_sold_out(data_root, portal):
    with pytest.raises(ValueError, match='warningi'):
        generate_foreign(LocalInputs(data_root), portal, 12)


def test_sqlite_missing_file_and_writes_are_rejected(data_root):
    with use(LocalInputs(data_root)):
        with read_connection(data_root/'databases/IDB.db') as conn:
            with pytest.raises(sqlite3.OperationalError):
                conn.execute("UPDATE EstateData SET Cena='1'")
        missing = data_root/'databases/missing.db'
        with pytest.raises(sqlite3.OperationalError):
            with read_connection(missing):
                pass
        assert not missing.exists()


def test_unsafe_local_paths_and_live_urls_are_rejected(data_root):
    from InvestmentManager.export_engine import runtime_paths
    from InvestmentManager.export_engine.local_io import urlopen, NetworkDisabledError
    with use(LocalInputs(data_root)):
        with pytest.raises(ValueError):
            runtime_paths.remote_offer_file(17,'../../../outside.txt')
        with pytest.raises(NetworkDisabledError):
            urlopen('https://example.invalid/image.jpg')
        with pytest.raises(NetworkDisabledError):
            urlopen('ftp://example.invalid/file.zip')


def test_all_transport_entrypoints_fail_closed(data_root):
    from InvestmentManager.export_engine.portals import service, workflows
    from InvestmentManager.export_engine import foreign_offers_export as foreign
    with pytest.raises(service.PortalUploadError):
        service.upload_portal_zip('domiporta','x.zip',b'abc')
    with pytest.raises(service.PortalUploadError):
        service.configure_secret_getter(lambda _: 'must-not-be-read')
    with pytest.raises(RuntimeError, match='Transport is disabled'):
        workflows.execute_no_workflow(None,None,None,None,None,None,'insert','Dodaj',upload=True)
    with pytest.raises(RuntimeError, match='Transport is disabled'):
        foreign.export_foreign_offer_to_domiporta(11,upload=True)
    assert not hasattr(foreign,'upload_foreign_withdrawal_package')
    assert not hasattr(foreign,'upload_cyprus_development_tabelaofert_package')
    assert not any(name.startswith('_log_export') for name in vars(foreign))


def test_imports_are_independent_of_ui_transport_and_production_paths(tmp_path):
    code = '''import builtins, sqlite3, sys
original = builtins.__import__

def no_connection(*args, **kwargs):
    raise AssertionError('Import must not open a database')
sqlite3.connect = no_connection
def guarded(name, *args, **kwargs):
    if name.split('.')[0] in {'streamlit', 'paramiko', 'ftplib', 'flask'}:
        raise AssertionError('Forbidden import: ' + name)
    return original(name, *args, **kwargs)
builtins.__import__ = guarded
import InvestmentManager.export_engine
import InvestmentManager.export_engine.generate
import InvestmentManager.export_engine.foreign_offers_export
from InvestmentManager.export_engine.runtime_paths import current
assert 'InvestmentManager._blueprint' not in sys.modules
assert not any(name.startswith('InvestmentManager.routes.') for name in sys.modules)
try: current()
except RuntimeError: print('explicit-inputs-required')
else: raise AssertionError('Implicit data root')
'''
    result = subprocess.run([sys.executable,'-B','-c',code],cwd=Path(__file__).resolve().parents[2],capture_output=True,text=True)
    assert result.returncode == 0, result.stderr
    assert result.stdout.strip() == 'explicit-inputs-required'


def test_no_sql_mutations_in_foreign_copy():
    from InvestmentManager.export_engine import foreign_offers_export as foreign
    tree = ast.parse(Path(foreign.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in {'commit','executescript','exec_command','open_sftp'}


def test_otodom_retains_original_unescaped_description_limitation(data_root):
    # COPY-only task: characterize the existing renderer defect, do not fix its
    # business output during environment adaptation. Renderer is byte-identical.
    (data_root/'offers/17/description_17.md').write_text('Opis & tekst', encoding='utf-8')
    _, content = generate_domestic(LocalInputs(data_root), 'otodom', 17)
    with zipfile.ZipFile(io.BytesIO(content)) as archive:
        xml = next(archive.read(n) for n in archive.namelist() if n.endswith('.xml'))
    assert b'<Description>Opis & tekst</Description>' in xml
    with pytest.raises(ET.ParseError):
        ET.fromstring(xml)


def test_explicit_dictionary_fixtures_do_not_leak_between_runs(data_root):
    from InvestmentManager.export_engine.generate import _environment
    from InvestmentManager.export_engine.portals.otodom.dictionaries import fetch_otodom_dictionaries, OTODOM_DICTIONARIES_URL
    for value in [b'{"dictionaries":{"fixture":"one"}}', b'{"dictionaries":{"fixture":"two"}}']:
        inputs = LocalInputs(data_root, url_responses={OTODOM_DICTIONARIES_URL: value})
        with _environment(inputs):
            import json
            assert fetch_otodom_dictionaries() == json.loads(value)['dictionaries']
