"""S3 / X7: offer descriptions (Markdown -> HTML) are sanitized with nh3 before they reach a template.

Covers: the PoC payloads, legitimate formatting that must survive (paragraphs, headings, lists, links, images, tables, code),
YouTube/Vimeo-only iframes, the fail-closed fallback, and the REAL templates (public offer page block + CRM card).
"""
import markdown
import pytest
from markupsafe import Markup

from modules.core import html_safety
from modules.core.html_safety import sanitize_description_html as clean

IMG = '<img src=x onerror=window.__xss=1>'


def _text(value):
    return str(clean(value))


# ------------------------------------------------------------------------------------------------ attacks neutralised
@pytest.mark.parametrize('payload', [
    IMG, '<script>window.__xss=1</script>', '<svg onload=window.__xss=1>', '<p onmouseover="window.__xss=1">t</p>', '<a href="javascript:window.__xss=1">x</a>',
    '<a href=" javascript:window.__xss=1">x</a>', '<a href="JaVaScRiPt:window.__xss=1">x</a>', '<a href="data:text/html,<script>1</script>">x</a>',
    '<iframe srcdoc="<script>window.__xss=1</script>"></iframe>', '<iframe src="javascript:window.__xss=1"></iframe>', '<object data="x"></object>',
    '<embed src="x">', '<form action="x"><input name=a></form>', '<style>*{background:url(javascript:1)}</style>', '<meta http-equiv=refresh content="0;url=x">',
    '<div style="position:fixed;inset:0" class="x">overlay</div>', '<base href="https://evil.test/">', '<link rel=stylesheet href=//evil.test/x.css>',
    '<math><mi xlink:href="javascript:1">x</mi></math>', '<img src="javascript:window.__xss=1">',
])
def test_payloads_become_inert(payload):
    out = _text(payload).lower()
    for needle in ('<script', 'onerror', 'onload', 'onmouseover', 'javascript:', 'srcdoc', '<svg', '<style', '<form', '<object', '<embed', '<meta', '<base', '<link',
                   'style=', 'class='):
        assert needle not in out, (payload, out)


def test_markdown_javascript_link_is_removed_after_rendering():
    out = _text(markdown.markdown('[kliknij](javascript:window.__xss=1) oraz [ok](https://example.test)'))
    assert 'javascript:' not in out and 'href="https://example.test"' in out and 'kliknij' in out        # the text stays, the active URL goes


def test_links_get_rel_and_protocol_relative_or_data_urls_are_handled():
    assert 'rel="noopener noreferrer nofollow"' in _text('<a href="https://example.test">x</a>')
    assert 'data:' not in _text('<a href="data:text/html,x">d</a>')


# ------------------------------------------------------------------------------------------------ legitimate formatting survives
def test_legitimate_markdown_formatting_is_preserved():
    source = '# Dom\n\nPiękny **dom** w *Łodzi* z ogrodem.\n\n* pokój\n* kuchnia\n\nLista numerowana:\n\n1. a\n2. b\n\n> cytat\n\n`kod` [oferta](https://example.test/a?b=1&c=2) ![plan](/static/images/7/plan.jpg "Plan")'
    out = _text(markdown.markdown(source))
    for fragment in ('<h1>Dom</h1>', '<strong>dom</strong>', '<em>Łodzi</em>', '<ul>', '<li>pokój</li>', '<ol>', '<blockquote>', '<code>kod</code>',
                     'href="https://example.test/a?b=1&amp;c=2"', 'src="/static/images/7/plan.jpg"', 'alt="plan"', 'title="Plan"'):
        assert fragment in out, fragment


def test_html_tables_images_and_polish_text_are_preserved():
    out = _text('<table><thead><tr><th>Pow.</th><th>Cena</th></tr></thead><tbody><tr><td colspan="2" align="center">Zażółć gęślą jaźń</td></tr></tbody></table>'
                '<p>Zdjęcie: <img src="https://cdn.example.test/a.jpg" alt="Łódź" width="300"></p><p>Linia<br>druga</p>')
    for fragment in ('<table>', '<th>Pow.</th>', 'colspan="2"', 'align="center"', 'Zażółć gęślą jaźń', 'width="300"', 'alt="Łódź"', '<br>'):
        assert fragment in out, fragment


def test_returns_markup_and_handles_empty_input():
    assert isinstance(clean('<p>x</p>'), Markup)
    assert str(clean(None)) == '' and str(clean('   ')) == ''


# ------------------------------------------------------------------------------------------------ iframes
@pytest.mark.parametrize('src', ['https://www.youtube.com/embed/dQw4w9WgXcQ', 'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?rel=0&start=10',
                                 'https://player.vimeo.com/video/123456789'])
def test_verified_video_embeds_are_kept_and_sandboxed(src):
    out = _text(f'<iframe src="{src}" width="560" height="315" allowfullscreen onload="window.__xss=1" style="x"></iframe>')
    assert f'src="{src.replace("&", "&amp;")}"' in out and 'sandbox="' in out and 'allowfullscreen' in out
    assert 'onload' not in out and 'style=' not in out


@pytest.mark.parametrize('src', ['https://evil.test/embed/x', 'http://www.youtube.com/embed/dQw4w9WgXcQ', 'https://www.youtube.com.evil.test/embed/dQw4w9WgXcQ',
                                 'https://evil.test/?u=https://www.youtube.com/embed/dQw4w9WgXcQ', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
                                 'https://player.vimeo.com/video/abc', '//www.youtube.com/embed/dQw4w9WgXcQ', 'javascript:window.__xss=1'])
def test_other_iframes_are_removed_entirely(src):
    out = _text(f'<p>przed</p><iframe src="{src}"></iframe><p>po</p>')
    assert '<iframe' not in out and 'przed' in out and 'po' in out


# ------------------------------------------------------------------------------------------------ fail closed
def test_without_nh3_the_text_is_escaped_not_passed_through(monkeypatch, caplog):
    monkeypatch.setattr(html_safety, 'nh3', None)
    monkeypatch.setattr(html_safety, '_warned', False)
    out = str(html_safety.sanitize_description_html(f'<p>ok</p>{IMG}'))
    assert '<img' not in out and '<p>' not in out and '&lt;img' in out
    assert any('nh3 is not installed' in r.getMessage() for r in caplog.records)


def test_requirement_is_pinned():
    from pathlib import Path
    requirements = (Path(__file__).resolve().parents[1] / 'requirements.txt').read_text(encoding='utf-8')
    assert any(line.strip().startswith('nh3==') for line in requirements.splitlines())


# ------------------------------------------------------------------------------------------------ the real templates
def test_public_offer_description_block_sanitizes(app):
    from flask import render_template
    html = markdown.markdown(f'Opis **domu**\n\n{IMG}\n\n<script>window.__xss=1</script>[x](javascript:window.__xss=1)')
    with app.test_request_context('/nieruchomosc/7'):
        page = render_template('components/offer_description_block.html', description_text=html, description_is_html=True)
    assert 'onerror' not in page and '<script' not in page and 'javascript:' not in page
    assert '<strong>domu</strong>' in page


def test_public_block_keeps_plain_text_escaped_and_html_formatting(app):
    from flask import render_template
    with app.test_request_context('/'):
        plain = render_template('components/offer_description_block.html', description_text=IMG, description_is_html=False)
        formatted = render_template('components/offer_description_block.html', description_text='<p>Akapit</p>\n\n<ul><li>jeden</li></ul>', description_is_html=True)
    assert IMG not in plain and '&lt;img' in plain
    assert '<p>Akapit</p>' in formatted and '<li>jeden</li>' in formatted


def test_crm_card_template_sanitizes_the_description(app):
    from pathlib import Path
    source = (Path(__file__).resolve().parents[1] / 'InvestmentManager' / 'templates' / 'investmentmanager' / 'offer_card_template.html').read_text(encoding='utf-8')
    assert '{{ description | sanitize_html }}' in source and '{{ description | safe }}' not in source
    rendered = app.jinja_env.from_string('{{ description | sanitize_html }}').render(description=markdown.markdown(f'x {IMG} **y**'))
    assert 'onerror' not in rendered and '<strong>y</strong>' in rendered


def test_no_template_marks_description_html_safe():
    """Guard: `| safe` must not be applied to description markup again (new templates should use sanitize_html)."""
    from pathlib import Path
    root = Path(__file__).resolve().parents[1]
    offenders = []
    for path in list((root / 'InvestmentWebsite' / 'templates').rglob('*.html')) + list((root / 'InvestmentManager' / 'templates').rglob('*.html')):
        for number, line in enumerate(path.read_text(encoding='utf-8-sig').splitlines(), 1):
            if '| safe' in line.replace('|safe', '| safe') and 'descr' in line.lower():
                offenders.append(f'{path.relative_to(root)}:{number}')
    assert offenders == []
