"""S3 regression: user-controlled data never reaches the HTML parser unescaped in the CRM front end (X1-X5, offers lead matching).

Each test runs the REAL script in node:vm with payloads from the PoC (tag injection, attribute break-out, javascript: URL) and ALSO
checks that legitimate data (Polish letters, ampersands, newlines) is still shown and that handlers still receive the original data.
"""
import json

import pytest

from tests.investmentmanager.js_dom_harness import ATTR, IMG, JS_URL, raw_html, run_js, shown_text

PL = 'Zażółć gęślą jaźń & spółka <ok> "cytat"'


# ------------------------------------------------------------------------------------------------ helper
def test_crm_escape_html_and_safe_href(tmp_path):
    result = run_js(tmp_path, [], f"""
        return {{
          escaped: crmEscapeHtml({json.dumps(IMG + ATTR)}),
          nullish: [crmEscapeHtml(null), crmEscapeHtml(undefined), crmEscapeHtml(0)],
          hrefs: [crmSafeHref('https://example.test/a?b=1&c=2'), crmSafeHref('/nieruchomosc/1'), crmSafeHref({json.dumps(JS_URL)}),
                  crmSafeHref('//evil.test/x'), crmSafeHref('/\\\\evil.test'), crmSafeHref(''), crmSafeHref('data:text/html,x', '#x')],
        }};""")['result']
    assert '<' not in result['escaped'] and '"' not in result['escaped'] and '&lt;img' in result['escaped']
    assert result['nullish'] == ['', '', '0']
    assert result['hrefs'] == ['https://example.test/a?b=1&c=2', '/nieruchomosc/1', '#', '#', '#', '#', '#x']


# ------------------------------------------------------------------------------------------------ X1 navbar alerts
ALERTS = f"""[{{read: false, level: 'info', timestamp: '2030-01-01T10:00:00', message: {json.dumps(f'Ann dodał nową notatkę: „{IMG}”')},
  metadata: {{[{json.dumps(IMG)}]: {json.dumps(IMG)}, 'Treść': {json.dumps(PL)}}}}}]"""


def test_x1_alert_message_and_metadata_are_text_not_html(tmp_path):
    result = run_js(tmp_path, ['navbar.js'], f"const alerts = {ALERTS}; updateHoverAlerts(alerts); updateNotificationModal(alerts); return alerts.length;")
    assert IMG not in raw_html(result)
    text = shown_text(result)
    assert IMG in text and PL in text                                   # displayed (as text), Polish and ampersands intact
    assert 'ℹ️' in text                                                  # the icon is still shown


def test_x1_alert_actions_still_work(tmp_path):
    result = run_js(tmp_path, ['navbar.js'], f"""
        const alerts = [{{read: true, level: 'warning', timestamp: 'T1', message: 'm', metadata: null}}];
        updateNotificationModal(alerts);
        return alerts[0].timestamp;""")
    assert result['result'] == 'T1'


# ------------------------------------------------------------------------------------------------ X3 calendar tooltip
def _event(**props):
    base = {'source_type': 'crm_meeting', 'description': 'Spotkanie', 'client_name': 'Jan', 'owner_agent_name': 'Ann', 'location_label': 'Biuro',
            'meeting_status': 'planned'}
    base.update(props)
    return json.dumps({'title': props.pop('title', 'CRM: Jan'), 'start': '2030-01-01T10:00:00', 'end': None, 'extendedProps': base})


def test_x3_tooltip_escapes_every_field(tmp_path):
    event = json.dumps({'title': f'CRM: {IMG}', 'start': '2030-01-01T10:00:00', 'end': None,
                        'extendedProps': {'source_type': 'crm_meeting', 'description': IMG, 'client_name': IMG + ATTR, 'owner_agent_name': IMG,
                                          'location_label': IMG, 'meeting_status': IMG}})
    result = run_js(tmp_path, ['agent_panel_scheduler.js'],
                    f"const ev = {event}; ev.start = new Date(ev.start); showCalendarTooltip(ev, document.createElement('div')); return 1;")
    html = raw_html(result)
    assert IMG not in html and 'onmouseover="window.__xss=1"' not in html and '&lt;img' in html


def test_x3_tooltip_keeps_legitimate_content(tmp_path):
    event = json.dumps({'title': 'CRM: Łukasz Żółć', 'start': '2030-01-01T10:00:00', 'end': None,
                        'extendedProps': {'source_type': 'crm_meeting', 'description': 'Dom & ogród\nDruga linia', 'client_name': PL, 'owner_agent_name': 'Zażółć',
                                          'location_label': 'ul. Długa 5', 'meeting_status': 'planned'}})
    html = raw_html(run_js(tmp_path, ['agent_panel_scheduler.js'], f"const ev = {event}; ev.start = new Date(ev.start); showCalendarTooltip(ev, document.createElement('div')); return 1;"))
    for fragment in ('CRM: Łukasz Żółć', 'Dom &amp; ogród', 'Zażółć gęślą jaźń &amp; spółka &lt;ok&gt; &quot;cytat&quot;', 'ul. Długa 5', 'Opiekun:', 'Klient:'):
        assert fragment in html


# ------------------------------------------------------------------------------------------------ X4 offer card + matching leads
OFFER = {'ID': 7, 'ID_agenta': 102, 'Status_oferty': 'aktywna', 'Typ_nieruchomosci': 'Dom', 'Typ_oferty': 'Sprzedaż', 'Typ_rynku': 'wtórny',
         'Data_dodania': '2030-01-01', 'Tytul': 'Dom w Łodzi & okolice', 'Cena': 1000, 'Miejscowosc': 'Łódź'}


def test_x4_offer_card_escapes_title_types_and_agent_name(tmp_path):
    offer = dict(OFFER, Tytul=IMG, Typ_nieruchomosci=IMG, Typ_oferty=ATTR, Typ_rynku=IMG, Data_dodania=IMG)
    result = run_js(tmp_path, ['offers_cards.js'],
                    f"cardsState.agentNamesById = {{102: {json.dumps(IMG)}}}; createOfferCard({json.dumps(offer)}); return 1;")
    html = raw_html(result)
    assert IMG not in html and 'onmouseover="window.__xss=1"' not in html and '&lt;img' in html


def test_x4_offer_card_keeps_legitimate_content(tmp_path):
    result = run_js(tmp_path, ['offers_cards.js'], f"cardsState.agentNamesById = {{102: 'Zażółć Gęślą'}}; createOfferCard({json.dumps(OFFER)}); return 1;")
    html = raw_html(result)
    for fragment in ('ID: 7', 'Dom na Sprzedaż', 'Rynek wtórny', 'Data dodania: 2030-01-01', 'Agent: (102) Zażółć Gęślą', 'Dom w Łodzi &amp; okolice'):
        assert fragment in html


def test_x2b_matching_leads_in_the_offer_view_are_escaped(tmp_path):
    leads = [{'name': IMG, 'phone': IMG, 'status': IMG}, {'name': 'Łukasz & Żaneta', 'phone': '500 100 200', 'status': 'nowy'}]
    html = run_js(tmp_path, ['offers_cards.js'], f"return renderMatchingLeadsHtml({json.dumps(leads)});")['result']
    assert IMG not in html and '&lt;img' in html
    assert 'Łukasz &amp; Żaneta' in html and '500 100 200' in html and 'Pasujące leady (2)' in html


# ------------------------------------------------------------------------------------------------ X5 document preview
@pytest.mark.parametrize('name', ['notes.txt', 'data.csv', 'config.json'])
def test_x5_text_preview_is_shown_as_text(tmp_path, name):
    url = f'/crm/offers/documents/7/file/{name}'
    result = run_js(tmp_path, ['offers_documents.js'], f"previewDocument(7, {json.dumps(name)}); return 1;", fetch={url: f'</pre>{IMG}\n{PL}'})
    assert IMG not in raw_html(result)
    text = shown_text(result)
    assert IMG in text and PL in text                                    # the file is displayed verbatim, as text


def test_x5_pdf_and_image_previews_still_use_an_encoded_url(tmp_path):
    result = run_js(tmp_path, ['offers_documents.js'], "previewDocument(7, 'plan 1&2.pdf'); previewDocument(7, 'zdjęcie.jpg'); return 1;")
    html = raw_html(result)
    assert '<iframe src="/crm/offers/documents/7/file/plan%201%262.pdf"' in html and '<img src="/crm/offers/documents/7/file/zdj%C4%99cie.jpg"' in html


# ------------------------------------------------------------------------------------------------ X2 leads list
def _lead(**values):
    lead = {'id': '20300101000000000001', 'created_by': 102, 'created_name': 'Ann Test', 'name': 'Jan Kowalski', 'phone': '500100200', 'status': 'nowy',
            'typ_nieruchomosci': ['dom'], 'typ_oferty': ['sprzedaż'], 'matching_estates': []}
    lead.update(values)
    return lead


def _run_leads(tmp_path, lead, scraped=None):
    return run_js(tmp_path, ['lead_hunter_seekers.js'], "currentUserId = '102'; loadLeads(); return 1;",
                  fetch={'/crm/leadhunter/get_scraped_offers': scraped or [], '/crm/leadhunter/get_leads': [lead]})


def test_x2_lead_fields_extra_keys_estates_and_olx_offers_are_escaped(tmp_path):
    lead = _lead(name=IMG, phone=IMG, status=IMG, created_name=IMG, typ_nieruchomosci=[IMG], **{'<b onmouseover=window.__xss=1>k</b>': IMG,
                 'matching_estates': [{'Tytul': IMG, 'Miejscowosc': IMG, 'Cena': IMG, 'ID': 1, 'Typ_nieruchomosci': IMG, 'Typ_oferty': IMG, 'Liczba_pokoi': IMG}]})
    scraped = [{'Tytul': IMG, 'Link': JS_URL, 'Miejscowosc': IMG, 'Cena': IMG, 'Powierzchnia': IMG, 'Typ oferty': IMG, 'Status oferty': IMG}]
    html = raw_html(_run_leads(tmp_path, lead, scraped))
    assert IMG not in html and '<b onmouseover' not in html and 'href="javascript:' not in html
    assert '&lt;img' in html


def test_x2_leads_keep_legitimate_content_and_action_buttons_use_listeners(tmp_path):
    lead = _lead(name='Łukasz & Żaneta', phone='500 100 200', status='nowy', created_name='Zażółć', Miejscowosc='Łódź')
    html = raw_html(_run_leads(tmp_path, lead))
    for fragment in ('Łukasz &amp; Żaneta', '500 100 200', 'Zażółć', 'Miejscowosc'.capitalize() + ':', 'Łódź', 'data-lead-action="edit"', 'data-lead-action="delete"'):
        assert fragment in html
    assert 'onclick=' not in html                                            # no data inside inline handlers any more


def test_x2_a_hostile_lead_id_cannot_break_out_of_a_handler(tmp_path):
    html = raw_html(_run_leads(tmp_path, _lead(id="1');window.__xss=1;('")))
    assert "window.__xss=1;(" not in html or 'onclick=' not in html          # the id is only used as an id attribute (escaped) and via listeners
    assert '&#39;);window.__xss=1;(&#39;' in html or "');window.__xss=1;('" not in html
