"""Feed integrity and publication guards, 2026.11.04.3."""
import json
import xml.etree.ElementTree as ET

import pytest

from timesheet import kufar as k

BASE = b'''<?xml version="1.0"?><uedb revision="5"><metadata source="legacy"/><records keep="yes"><record custom="true"><unid>old-1</unid><subject>Old title</subject><body>Long enough description for an existing ad.</body><price>15.00</price><category>15020</category><special a="1"><child>Keep me</child></special><photos other="keep"><photo picture="https://example.com/one.jpg" checksum="keep"/></photos></record></records></uedb>'''


def test_category_search_index_includes_nested_product_types():
    assert 'Роботы-пылесосы' in k.categories()['15030']['search']


def test_standard_description_is_optional_and_never_duplicated():
    body='Описание дефекта'
    combined=k.with_standard_description(body)
    assert combined.endswith(k.STANDARD_DESCRIPTION_TEXT)
    assert k.with_standard_description(combined)==combined
    assert k.with_standard_description(body,False)==body


class Remote:
    data = BASE
    uploads = 0
    def __init__(self, config): pass
    def __enter__(self): return self
    def __exit__(self, *args): pass
    def read(self, path): return self.data
    def publish(self, path, data, baseline):
        assert baseline == self.data
        type(self).data = data
        type(self).uploads += 1


@pytest.fixture
def workspace(tmp_path):
    Remote.data = BASE
    Remote.uploads = 0
    with k.connect(tmp_path) as c:
        c.execute("UPDATE state SET config=?,manual_count=275", (json.dumps({"feed_path":"kufar.xml"}),))
        k.reconcile(c,1,Remote)
    return tmp_path


def edit(c, removed=False):
    s = k.snapshot(c)
    row = s['rows'][0]
    d = k.fields(k.parse(s['baseline'])[1][row['unid']])
    d['subject'] = 'Changed & title'
    k.save_listing(c,row['unid'],row['version'],s['revision'],d,removed,'8369615-расп-1939552',1)


def test_roundtrip_preserves_unknown_tags_and_photo_metadata(workspace):
    with k.connect(workspace) as c:
        edit(c)
        s = k.snapshot(c)
        output = k.build(s['baseline'],s['rows'])
        r,items = k.parse(output)
        assert r.attrib == {'revision':'5'}
        assert r.find('metadata').get('source') == 'legacy'
        assert r.find('records').get('keep') == 'yes'
        ad = items['old-1']
        assert ad.findtext('subject') == 'Changed & title'
        assert ad.findtext('special/child') == 'Keep me'
        assert ad.find('photos').get('other') == 'keep'
        assert ad.find('photos/photo').get('checksum') == 'keep'


@pytest.mark.parametrize('data', [b'<uedb><records><record><unid/></record></records></uedb>',b'<uedb><records><record><unid>a</unid></record><record><unid>a</unid></record></records></uedb>',b'<!DOCTYPE x [<!ENTITY e "bad">]><uedb><records/></uedb>',b'<uedb><records/><records/></uedb>',b'<html/>',b''])
def test_invalid_xml_does_not_become_baseline(data):
    with pytest.raises(k.Error): k.parse(data)


def test_remote_conflict_never_overwrites(workspace):
    with k.connect(workspace) as c:
        edit(c)
        Remote.data = BASE.replace(b'Old title',b'External change')
        with pytest.raises(k.Error,match='вне приложения'):
            k.publish(c,k.snapshot(c)['revision'],1,Remote)
        assert Remote.uploads == 0
        assert k.snapshot(c)['rows'][0]['draft']


def test_pending_edits_block_resync(workspace):
    with k.connect(workspace) as c:
        edit(c)
        with pytest.raises(k.Error,match='локальные изменения'): k.reconcile(c,1,Remote)


def test_stale_editor_is_rejected(workspace):
    with k.connect(workspace) as c:
        s=k.snapshot(c)
        edit(c)
        with pytest.raises(k.Error,match='изменилась'):
            k.save_listing(c,'old-1',0,s['revision'],{},False,'',2)


def test_removed_listing_archived_only_after_publish(workspace):
    with k.connect(workspace) as c:
        edit(c,removed=True)
        assert len(k.parse(Remote.data)[1]) == 1
        k.publish(c,k.snapshot(c)['revision'],1,Remote)
        assert not k.parse(Remote.data)[1]
        assert not k.snapshot(c)['rows']
        assert c.execute('SELECT count(*) FROM archive').fetchone()[0] == 1


def test_activate_complete_candidate_then_refresh_price_and_stock(workspace):
    candidate=workspace/'candidate';candidate.mkdir()
    root,records=k.parse(BASE)
    second=ET.fromstring(ET.tostring(records['old-1']))
    second.find('unid').text='KF2';second.find('subject').text='Second product'
    root.find('records').append(second)
    data=ET.tostring(root,encoding='utf-8',xml_declaration=True)
    (candidate/'kufar-full-candidate.xml').write_bytes(data)
    report=dict(records=2,category_blockers=0,mapping=[
        dict(unid='old-1',product_id='123-расп-456'),dict(unid='KF2',product_id='')])
    (candidate/'report.json').write_text(json.dumps(report),encoding='utf-8')
    with k.connect(workspace) as c:
        count=k.activate_full_candidate(c,candidate,k.snapshot(c)['revision'],1,Remote)
        assert count==2 and k.snapshot(c)['manual_count']==0 and len(k.snapshot(c)['rows'])==2
        result=k.refresh_prices_and_stock(c,k.snapshot(c)['revision'],
            {'123-расп-456':dict(is_active=True,site_price='20.25')},1,Remote)
        assert result['updated']==1 and result['unbound']==1
        assert k.parse(Remote.data)[1]['old-1'].findtext('price')=='20.25'
        result=k.refresh_prices_and_stock(c,k.snapshot(c)['revision'],{},1,Remote)
        assert result['removed']==1 and 'old-1' not in k.parse(Remote.data)[1]


def test_prominent_removal_action_can_be_reversed_before_publish(workspace):
    with k.connect(workspace) as c:
        row=k.snapshot(c)['rows'][0]
        message=k.set_removed(c,row['unid'],row['version'],k.snapshot(c)['revision'],True,1)
        assert 'подготовлено к снятию' in message
        row=k.snapshot(c)['rows'][0]
        assert row['removed']
        k.set_removed(c,row['unid'],row['version'],k.snapshot(c)['revision'],False,1)
        assert not k.snapshot(c)['rows'][0]['removed']
        assert len(k.parse(Remote.data)[1])==1


def test_combined_manual_limit(workspace):
    with k.connect(workspace) as c:
        edit(c)
        c.execute('UPDATE state SET manual_count=300')
        with pytest.raises(k.Error,match='лимит 300'):
            k.publish(c,k.snapshot(c)['revision'],1,Remote)
        assert Remote.uploads == 0


def test_missing_manual_count_blocks_publish(workspace):
    with k.connect(workspace) as c:
        edit(c)
        c.execute('UPDATE state SET manual_count=NULL')
        with pytest.raises(k.Error,match='ручных объявлений'):
            k.publish(c,k.snapshot(c)['revision'],1,Remote)


def test_full_nomenclature_extraction_without_sku_guess(tmp_path):
    Remote.data = BASE.replace(b'Long enough description', '8369615-расп-1939552 Long enough description'.encode())
    with k.connect(tmp_path) as c:
        c.execute('UPDATE state SET config=?',(json.dumps({'feed_path':'a'}),))
        k.reconcile(c,1,Remote)
        assert k.snapshot(c)['rows'][0]['product_id'] == '8369615-расп-1939552'


def test_new_unid_is_exact_product_code_and_whole_feed_retained(workspace):
    values=dict(category='15020',subject='A refrigerator',body='Real condition and defects description.',price='45,50',photos='https://example.com/actual.jpg',phone='+375445012104',contact_person='Shop',area='22',parameter_condition='1',parameter_large_appliance_type='20',parameter_shop_guarantee='1 месяц',parameter_shop_manufacturer='ООО Производитель')
    with k.connect(workspace) as c:
        k.create_listing(c,k.snapshot(c)['revision'],'123-расп-456',values,1)
        s=k.snapshot(c)
        assert len(k.parse(k.build(s['baseline'],s['rows']))[1]) == 2
        with pytest.raises(k.Error,match='уже есть'):
            k.create_listing(c,s['revision'],'123-расп-456',values,1)
        k.publish(c,s['revision'],1,Remote)
        items=k.parse(Remote.data)[1]
        assert 'old-1' in items and '123RASP456' in items
        assert items['123RASP456'].findtext('price') == '45.50'
        assert '123-расп-456' in items['123RASP456'].findtext('body')
        assert items['123RASP456'].findtext('condition') == '1'
        assert items['123RASP456'].findtext('shop_guarantee') == '1 месяц'
        assert items['123RASP456'].findtext('shop_manufacturer') == 'ООО Производитель'


def test_mixed_photo_plan_preserves_main_and_following_order():
    raw = json.dumps([
        {'kind':'file','index':1},
        {'kind':'url','value':'https://example.com/second.jpg'},
        {'kind':'file','index':0},
    ])
    assert k.photo_plan(raw,['https://example.com/second.jpg'],2) == [
        ('file',1),('url','https://example.com/second.jpg'),('file',0)
    ]


@pytest.mark.parametrize('raw,urls,count', [
    ('', ['https://example.com/a.jpg'] * 2, 0),
    (json.dumps([{'kind':'file','index':0}]), [], 2),
    (json.dumps([{'kind':'url','value':'https://example.com/other.jpg'}]), ['https://example.com/a.jpg'], 0),
])
def test_invalid_photo_order_is_rejected(raw,urls,count):
    with pytest.raises(k.Error):
        k.photo_plan(raw,urls,count)


def test_photo_limit_and_duplicate_validation():
    draft=dict(subject='Valid title',body='Long enough description for a listing.',price='1',photos=['https://example.com/a.jpg'] * 2)
    with pytest.raises(k.Error,match='несколько раз'):
        k.validate(draft)
    draft['photos']=[f'https://example.com/{index}.jpg' for index in range(k.MAX_PHOTOS+1)]
    with pytest.raises(k.Error,match='не более'):
        k.validate(draft)


def test_ascii_nomenclature_transport_key():
    assert k.import_unid('10142911-БК-2585436') == '10142911BK2585436'
    assert k.import_unid('8369615-расп-1939552') == '8369615RASP1939552'


def test_ftp_does_not_delete_original_when_rename_fails():
    class FTP:
        def rename(self,a,b): raise OSError('unsupported overwrite')
        def delete(self,*args): pytest.fail('Must never delete original feed')
    remote=k.Remote({})
    remote.ftp=FTP()
    remote.write_verified=lambda path,data: None
    remote.read=lambda path: BASE
    with pytest.raises(OSError): remote.publish('kufar.xml',b'new',BASE)


def test_password_encryption_roundtrip():
    encrypted=k.protect('not-a-real-password')
    assert 'not-a-real-password' not in encrypted
    assert k.protect(encrypted,True) == 'not-a-real-password'
