"""Generator regression against the synthetic pre-016 byte-parity oracle."""
from contextlib import closing
import hashlib
import io
import json
import os
from pathlib import Path
import sqlite3
from urllib.parse import urlsplit
from urllib.request import url2pathname
import xml.etree.ElementTree as ET
import zipfile

import pytest

from InvestmentManager.export_engine import foreign_offers_export as copied
from InvestmentManager.export_engine.generate import generate_foreign, generate_cyprus, generate_withdrawal, _environment
from InvestmentManager.export_engine.runtime_paths import LocalInputs
from .foreign_parity_support import frozen_clock, frozen_opener

SINGLE = ['base', 'update', 'tripinvest', 'avarten', 'house', 'plot', 'commercial',
          'floor_zero', 'floor_minus_one', 'floor_null', 'override_zero', 'override_minus_one',
          'currency_PLN', 'currency_EUR', 'currency_USD', 'currency_GBP', 'currency_CHF',
          'currency_SEK', 'currency_THB', 'currency_AED', 'currency_BAD',
          'secondary', 'unknown_market', 'inactive', 'sold_out', 'resolved_sold_out',
          'no_images', 'gallery_order', 'partial_images', 'all_images_fail', 'corrupt_image',
          'agent_fallback', 'agent_partial', 'agent_missing', 'agent_inactive',
          'no_project', 'reassigned_project', 'renamed_project', 'no_category',
          'blocking_warning', 'description_cdata', 'description_empty', 'old_optional_schema']
GROUP = ['base', 'mixed_categories', 'inactive_member', 'all_sold_out', 'partial_images',
         'no_images', 'bad_price', 'bad_floor', 'reassigned_project', 'renamed_project',
         'added_member', 'bad_currency', 'agent_fallback']
WITHDRAW = ['inactive', 'sold_out', 'active', 'not_published', 'missing_offer',
            'resolved_sold_out', 'reassigned_project', 'changed_category']
CASES = [('single', p, v) for p in ('domiporta', 'tabelaofert') for v in SINGLE]
CASES += [('group', 'tabelaofert', v) for v in GROUP]
CASES += [('withdraw', p, v) for p in ('domiporta', 'tabelaofert') for v in WITHDRAW]


def execute(root, sql, args=()):
    with closing(sqlite3.connect(root / 'databases/foreign_offers.db')) as conn, conn:
        conn.execute(sql, args)


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


def configure(root, kind, variant):
    def update(**values):
        execute(root, 'UPDATE foreign_offers SET ' + ','.join(k + '=?' for k in values) + ' WHERE id=11', tuple(values.values()))
    if kind == 'withdraw':
        update(is_active=0)
        if variant == 'sold_out':
            update(is_active=1)
            execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking) VALUES (11,'source_sold_out','Sold Out',1)")
        elif variant == 'active': update(is_active=1)
        elif variant == 'not_published': execute(root, 'UPDATE foreign_offer_portal_sync SET is_published=0 WHERE foreign_offer_id=11')
        elif variant == 'missing_offer': execute(root, 'DELETE FROM foreign_offers WHERE id=11')
        elif variant == 'resolved_sold_out':
            update(is_active=1)
            execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking,resolved_at) VALUES (11,'source_sold_out','Sold Out',1,'2026-10-26')")
        elif variant == 'changed_category': update(category_id_domiporta='193', property_type_source='plot')
    if variant in ('tripinvest', 'avarten'): update(source_platform=variant)
    if variant == 'update': update(price_value=177000, offer_description='Nowy opis')
    if variant in ('house', 'plot', 'commercial'):
        category, label = {'house': ('192', 'villa'), 'plot': ('193', 'plot'), 'commercial': ('196', 'office')}[variant]
        update(category_id_domiporta=category, property_type_source=label)
    if variant == 'floor_zero': update(floor=0, floor_override=None)
    if variant == 'floor_minus_one': update(floor=-1, floor_override=None)
    if variant in ('floor_null', 'bad_floor'): update(floor=None, floor_override=None)
    if variant == 'override_zero': update(floor=3, floor_override=0)
    if variant == 'override_minus_one': update(floor=3, floor_override=-1)
    if variant.startswith('currency_'): update(price_currency=variant.split('_', 1)[1])
    if variant == 'bad_currency': update(price_currency='BAD')
    if variant == 'secondary': update(market_type_normalized='secondary')
    if variant == 'unknown_market': update(market_type_normalized='unknown')
    if variant in ('inactive', 'inactive_member') and kind != 'withdraw': update(is_active=0)
    if variant in ('sold_out', 'all_sold_out') and kind != 'withdraw':
        execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking) VALUES (11,'source_sold_out','Sold Out',1)")
        if variant == 'all_sold_out':
            execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking) VALUES (13,'source_sold_out','Sold Out',1)")
    if variant == 'resolved_sold_out' and kind != 'withdraw':
        execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking,resolved_at) VALUES (11,'source_sold_out','Sold Out',1,'2026-10-26')")
    if variant == 'no_images': execute(root, 'DELETE FROM foreign_offer_images WHERE foreign_offer_id=11')
    if variant == 'gallery_order':
        execute(root, 'INSERT INTO foreign_offer_images(foreign_offer_id,image_url,sort_order) VALUES (11,?,-2)',
                ((root / 'offers/17/image_17_url_1.jpg').as_uri(),))
        execute(root, 'INSERT INTO foreign_offer_images(foreign_offer_id,image_url,sort_order) VALUES (11,?,0)',
                ((root / 'offers/17/image_17_url_0.jpg').as_uri(),))
    if variant in ('partial_images', 'all_images_fail', 'corrupt_image'):
        if variant == 'partial_images':
            execute(root, "INSERT INTO foreign_offer_images(foreign_offer_id,image_url,sort_order) VALUES (11,'https://media.example.invalid/missing.jpg',-1)")
        else:
            execute(root, 'UPDATE foreign_offer_images SET image_url=? WHERE foreign_offer_id=11',
                    ('https://media.example.invalid/' + ('corrupt.jpg' if variant == 'corrupt_image' else 'missing.jpg'),))
    if variant == 'agent_fallback': update(agent_identifier='7', agent_name=None, agent_email=None, agent_phone=None)
    if variant == 'agent_partial': update(agent_identifier='7', agent_name='Manual Agent', agent_email=None, agent_phone='700 100 200')
    if variant == 'agent_missing': update(agent_identifier='999', agent_name=None, agent_email=None, agent_phone=None)
    if variant == 'agent_inactive':
        update(agent_identifier='7', agent_name=None, agent_email=None, agent_phone=None)
        with closing(sqlite3.connect(root / 'databases/agents.db')) as conn, conn:
            conn.execute('UPDATE agents_v2 SET is_active=0 WHERE id=7')
    if variant == 'no_project': update(development_id=None)
    if variant in ('reassigned_project', 'renamed_project'):
        if variant == 'renamed_project': execute(root, "UPDATE foreign_developments SET name='Renamed & <Project>' WHERE id=7")
        else:
            execute(root, "INSERT INTO foreign_developments(id,name,source_platform,source_key) VALUES (9,'New Project','cyprus_constructions','new')")
            update(development_id=9)
    if variant == 'no_category': update(category_id_domiporta=None)
    if variant == 'blocking_warning':
        execute(root, "INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message,is_blocking) VALUES (11,'missing_city_name','Missing city',1)")
    if variant == 'description_cdata': update(offer_description='A ]]> B & <b>tekst</b>\r\n Łódź', offer_title='Test & title')
    if variant == 'description_empty': update(offer_description=None)
    if variant == 'bad_price': update(price_value=0)
    if variant == 'old_optional_schema':
        execute(root, 'ALTER TABLE foreign_offers DROP COLUMN floor_override')
        execute(root, 'ALTER TABLE foreign_offers DROP COLUMN development_id')
    if variant in ('added_member', 'mixed_categories'):
        with closing(sqlite3.connect(root / 'databases/foreign_offers.db')) as conn, conn:
            conn.row_factory = sqlite3.Row
            row = dict(conn.execute('SELECT * FROM foreign_offers WHERE id=13').fetchone())
            row.update(id=14, source_url='https://cyprus.example.invalid/project#unit-type=14', source_offer_ref='14')
            conn.execute('INSERT INTO foreign_offers(' + ','.join(row) + ') VALUES (' + ','.join('?' for _ in row) + ')', tuple(row.values()))
            conn.execute('INSERT INTO foreign_offer_images(foreign_offer_id,image_url,sort_order) SELECT 14,image_url,sort_order FROM foreign_offer_images WHERE foreign_offer_id=13')
        if variant == 'mixed_categories':
            update(category_id_domiporta='193', property_type_source='plot')
            execute(root, "UPDATE foreign_offers SET category_id_domiporta='192',property_type_source='villa' WHERE id=13")
            execute(root, "UPDATE foreign_offers SET category_id_domiporta='193',property_type_source='plot' WHERE id=14")


def frozen_responses(root):
    responses = {}
    with closing(sqlite3.connect(root / 'databases/foreign_offers.db')) as conn, conn:
        for row_id, uri in conn.execute('SELECT id,image_url FROM foreign_offer_images').fetchall():
            if uri.startswith('file:'):
                body = Path(url2pathname(urlsplit(uri).path)).read_bytes()
                url = f'https://media.example.invalid/{row_id}.jpg'
                conn.execute('UPDATE foreign_offer_images SET image_url=? WHERE id=?', (url, row_id))
                responses[url] = {'body': body, 'status': 200, 'seconds': 0.01, 'redirects': ()}
    responses['https://media.example.invalid/corrupt.jpg'] = {'body': b'not an image', 'status': 200, 'seconds': 0.01, 'redirects': ()}
    return responses


def outcome(call):
    try: return {'value': call()}
    except Exception as exc: return {'error': type(exc).__name__, 'message': str(exc)}


@pytest.mark.parametrize('kind,portal,variant', CASES, ids=['/'.join(case) for case in CASES])
def test_actual_generators_byte_parity(data_root, monkeypatch, kind, portal, variant):
    configure(data_root, kind, variant)
    responses = frozen_responses(data_root)
    opener = frozen_opener(responses, allowed_hosts={'media.example.invalid'})
    base_url = 'https://investment.example.invalid/base'
    before = digest_files(data_root)
    inputs = LocalInputs(data_root, website_base_url=base_url,
                         url_responses={url: item['body'] for url, item in responses.items()})
    with frozen_clock(monkeypatch):
        monkeypatch.setattr(copied,'urlopen',opener)
        if kind == 'single':
            old = outcome(lambda: generate_foreign(inputs,portal,11))
        elif kind == 'group':
            old = outcome(lambda: generate_cyprus(inputs,7))
        else:
            old = outcome(lambda: generate_withdrawal(inputs,portal,11))
    assert digest_files(data_root) == before
    value = old.get('value')
    content = value[1] if isinstance(value, tuple) else value.get('zip_bytes') if isinstance(value, dict) else None
    record = {'case': '/'.join((kind, portal, variant)), 'classification': 'MATCHED REJECTION',
              'zip_entries': {}, 'xml_errors': {}}
    if content is not None:
        assert isinstance(content, bytes)
        record.update(classification='BYTE MATCH', zip_sha256=hashlib.sha256(content).hexdigest(),
                      zip_name=value[0] if isinstance(value, tuple) else value['zip_filename'])
        with zipfile.ZipFile(io.BytesIO(content)) as archive:
            assert archive.testzip() is None
            for name in archive.namelist():
                body = archive.read(name)
                record['zip_entries'][name] = hashlib.sha256(body).hexdigest()
                if name.endswith('.xml'):
                    try:
                        ET.fromstring(body)
                    except ET.ParseError as exc:
                        # Both raw artifacts were compared above. This deliberately
                        # adversarial input exposes the identical legacy CDATA bug;
                        # parity is not evidence of well-formed XML or portal acceptance.
                        assert kind == 'single' and portal == 'domiporta' and variant == 'description_cdata'
                        record['xml_errors'][name] = str(exc)
        if portal == 'domiporta': assert not any(n.endswith('.jpg') for n in record['zip_entries'])
        if kind == 'single' and variant == 'partial_images' and portal == 'tabelaofert':
            assert len([n for n in record['zip_entries'] if n.endswith('.jpg')]) == 1
        if kind == 'group' and variant == 'mixed_categories':
            xml = ET.fromstring(zipfile.ZipFile(io.BytesIO(content)).read('oferty.xml'))
            assert [node.findtext('id') for node in xml.findall('./lista_ofert/dzial/oferta')] == ['foreign_11', 'foreign_14', 'foreign_13']
    else:
        assert 'error' in old or value.get('ready') is False
        record['refusal'] = old.get('message') or value['problems']
    golden=json.loads((Path(__file__).parent/'foreign-golden.json').read_text(encoding='utf8'))
    assert json.loads(json.dumps(record,ensure_ascii=False)) == golden[record['case']]
    folder = os.environ.get('IDB_INT008_EVIDENCE')
    if folder:
        target = Path(folder).resolve()
        assert target.is_dir() and not target.is_relative_to(data_root)
        with (target / 'parity-matrix.jsonl').open('a', encoding='utf8') as stream:
            stream.write(json.dumps(record, ensure_ascii=False) + '\n')


@pytest.mark.parametrize('portal', ['domiporta', 'tabelaofert'])
def test_real_bulk_wrappers_keep_partial_success_and_categories(data_root, monkeypatch, portal):
    configure(data_root, 'group', 'mixed_categories')
    responses = frozen_responses(data_root)
    opener = frozen_opener(responses, allowed_hosts={'media.example.invalid'})
    base_url = 'https://investment.example.invalid/base'
    inputs = LocalInputs(data_root, website_base_url=base_url)
    before = digest_files(data_root)
    ids = [11, 13, 14, 12, 9999]
    method = 'export_many_foreign_offers_to_' + portal
    with frozen_clock(monkeypatch):
        monkeypatch.setattr(copied,'urlopen',opener)
        with _environment(inputs):
            old = getattr(copied,method)(ids,upload=False)
    assert digest_files(data_root) == before
    results, errors = old
    assert list(results) == [11, 13, 14] and set(errors) == {12, 9999}
    record = {'case': 'bulk/' + portal + '/mixed_categories', 'classification': 'BYTE MATCH',
              'zip_packages': {}, 'matched_refusals': errors, 'xml_errors': {}}
    for offer_id, (name, body, summary) in results.items():
        package = {'name': name, 'zip_sha256': hashlib.sha256(body).hexdigest(), 'entries': {}}
        with zipfile.ZipFile(io.BytesIO(body)) as archive:
            assert archive.testzip() is None
            for entry in archive.namelist():
                content = archive.read(entry)
                package['entries'][entry] = hashlib.sha256(content).hexdigest()
                if entry.endswith('.xml'): ET.fromstring(content)
        record['zip_packages'][str(offer_id)] = package
    golden=json.loads((Path(__file__).parent/'foreign-golden.json').read_text(encoding='utf8'))
    assert json.loads(json.dumps(record,ensure_ascii=False)) == golden[record['case']]
    folder = os.environ.get('IDB_INT008_EVIDENCE')
    if folder:
        target = Path(folder).resolve()
        assert target.is_dir() and not target.is_relative_to(data_root)
        with (target / 'parity-matrix.jsonl').open('a', encoding='utf8') as stream:
            stream.write(json.dumps(record, ensure_ascii=False) + '\n')
