"""INV-SEC-001 / INV-AUD-001: public lead/phone-view data cannot inject HTML into the CRM leads panel.

Two layers: the public endpoints keep only http(s) URLs and bounded fields, and
leady_logs.js escapes every interpolated value. The JS test runs the real
leady_logs.js in node:vm with a minimal DOM stub (skipped without node).
The platform_logs DB is redirected to tmp by the session fixture in conftest.
"""
import json
import shutil
import subprocess
import uuid
from datetime import datetime, timedelta
from itertools import count
from pathlib import Path

import pytest

import InvestmentWebsite.blueprints.platform.platform as platform_module
from modules.core.extensions import limiter
from InvestmentWebsite.offers import lead_spam_guard
from InvestmentWebsite.offers.platform_facade import MAX_PLATFORM_LENGTH, MAX_URL_LENGTH, safe_http_url

REPO_ROOT = Path(__file__).resolve().parents[2]
XSS = '"><img src=x onerror=alert(document.domain)>'


@pytest.fixture(autouse=True)
def _local_message_ids(monkeypatch):
    import flask_mail

    # Message construction/rendering remains real; do not resolve the host
    # name merely to construct a synthetic message identifier.
    ids = count(1)
    monkeypatch.setattr(flask_mail, "make_msgid", lambda: f"<leads-panel-{next(ids)}@example.invalid>")


@pytest.fixture(autouse=True)
def _isolated_storage(tmp_path, monkeypatch):
    """Own platform_logs.db and leads inbox per test: the session-wide platform log
    file is shared with tests that expect to be its only writer."""
    from modules.core import storage_paths

    monkeypatch.setenv(storage_paths.DATA_DIR_ENV_VAR, str(tmp_path))
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    monkeypatch.setattr(storage_paths, "platform_logs_dir", lambda: tmp_path / "platform_logs")
    monkeypatch.setattr(storage_paths, "platform_logs_db_path", lambda: tmp_path / "platform_logs" / "platform_logs.db")
    (tmp_path / "platform_logs").mkdir()


# ---------------------------------------------------------------------------
# URL validation
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("url", [
    "https://tripinvest.pl/oferta/apartament-w-torrevieja-75156",
    "http://investment-nieruchomosci.com/nieruchomosci/cypr/projekt/aHR0cHM6Ly9leGFtcGxl?x=1&y=%22a%22#top",
    "https://avartenproperties.com/property/laya-courtyard/",
    "HTTPS://Example.com/Path",
])
def test_real_page_urls_are_kept_unchanged(url):
    assert safe_http_url(url) == url


@pytest.mark.parametrize("value", [
    None, "", "   ",
    "javascript:alert(1)",
    "JaVaScRiPt:alert(1)",
    "data:text/html,<script>alert(1)</script>",
    "/relative/path",
    "//evil.example/x",
    "https://",
    "https://example.com/" + XSS,
    'https://example.com/"onmouseover="x',
    "https://example.com/a b",
    "https://example.com/\nx",
    "https://example.com/" + "a" * MAX_URL_LENGTH,
])
def test_non_http_or_markup_urls_are_dropped(value):
    assert safe_http_url(value) == ""


# ---------------------------------------------------------------------------
# Public endpoints
# ---------------------------------------------------------------------------


def _crm_items(client, monkeypatch=None):
    with client.session_transaction() as sess:
        sess["user_id"] = 1
        sess["access_level"] = "master"
    return client.get("/crm/leady/platform_logs?per_page=200").get_json()["items"]


def test_phone_view_stores_only_the_url_without_query_values(client):
    marker = uuid.uuid4().hex
    page = f"https://investment.example/nieruchomosci/cypr/{marker}?t=private-value"
    response = client.post("/api/platform_phone_view", data={
        "platform": "cyprus", "offer_url": "https://cyprusconstructions.com/projects/aloha",
        "platform_page_url": page,
    })
    assert response.status_code == 200 and response.get_json() == {"success": True}

    item = next(i for i in _crm_items(client) if marker in i["platform_page_url"])
    assert item["platform_page_url"] == f"https://investment.example/nieruchomosci/cypr/{marker}"
    assert item["offer_url"] == "https://cyprusconstructions.com/projects/aloha"
    assert item["platform"] == "cyprus"


def test_phone_view_with_malicious_fields_is_accepted_but_neutralised(client):
    marker = uuid.uuid4().hex
    response = client.post(
        "/api/platform_phone_view",
        data={"platform": f"{marker}{XSS}" + "p" * 500, "offer_url": XSS,
              "platform_page_url": f"javascript:alert('{marker}')"},
        headers={"User-Agent": "U" * 5000},
    )
    assert response.status_code == 200  # logging a view never fails the visitor

    item = next(i for i in _crm_items(client) if i["platform"].startswith(marker))
    assert item["offer_url"] == ""
    assert item["platform_page_url"] == ""
    assert len(item["platform"]) == MAX_PLATFORM_LENGTH
    assert "user_agent" not in item["payload"]


def test_lead_is_still_sent_and_urls_are_validated(app, client, monkeypatch):
    sent = []
    monkeypatch.setattr(platform_module.mail, "send", sent.append)
    monkeypatch.setenv("MAIL_USERNAME", "crm@example.invalid")  # recipients only; nothing is sent
    marker = uuid.uuid4().hex

    class Later(datetime):
        @classmethod
        def now(cls, tz=None):
            return datetime.now(tz) + timedelta(seconds=30)

    monkeypatch.setattr(lead_spam_guard, "datetime", Later)
    with app.test_request_context():
        token = lead_spam_guard.issue_form_token()

    good = client.post("/api/platform_send_lead", data={
        "platform": "tripinvest", "phone": "600100200", "email": "jan@example.com",
        "message": f"Proszę o kontakt {marker}", "offer_url": "https://tripinvest.pl/oferta/x-1",
        "platform_page_url": "https://investment.example/hiszpania", "form_token": token,
    })
    bad = client.post("/api/platform_send_lead", data={
        "platform": "tripinvest", "phone": "600100200",
        "message": f"<b>{marker}</b>", "offer_url": XSS, "platform_page_url": "javascript:x",
        "form_token": token,
    })

    assert good.status_code == 200 and bad.status_code == 400
    assert len(sent) == 1
    items = [i for i in _crm_items(client) if marker in (i["phone_message"] or "")]
    by_message = {i["phone_message"]: i for i in items}
    assert by_message[f"Proszę o kontakt {marker}"]["offer_url"] == "https://tripinvest.pl/oferta/x-1"
    assert f"<b>{marker}</b>" not in by_message


@pytest.fixture()
def limited_app(app):
    limiter.enabled = True
    limiter.reset()
    try:
        yield app
    finally:
        limiter.reset()
        limiter.enabled = False


def test_phone_view_is_rate_limited_per_ip(limited_app):
    client = limited_app.test_client()
    statuses = [client.post("/api/platform_phone_view", data={"platform": "cyprus"}).status_code for _ in range(21)]
    assert statuses[:20] == [200] * 20
    assert statuses[20] == 429


# ---------------------------------------------------------------------------
# leady_logs.js rendering (real file, node:vm, minimal DOM stub)
# ---------------------------------------------------------------------------

_NODE_HARNESS = r"""
const fs = require("fs");
const vm = require("vm");
const [, , scriptPath, itemsJson, scope] = process.argv;

function element(tag) {
  return {
    tag, children: [], className: "", innerHTML: "", textContent: "", value: "",
    classList: { add() {}, remove() {} },
    appendChild(child) { this.children.push(child); return child; },
    addEventListener() {}, setAttribute() {}, removeAttribute() {},
    querySelector() { return null; },
  };
}
const list = element("div");
const context = {
  console, Number, String, Array, JSON, Date, URLSearchParams,
  document: {
    getElementById: (id) => (id === "leady-list-body" ? list : null),
    createElement: element,
    addEventListener() {},
    body: element("body"),
  },
  window: {},
  fetch: async () => ({ ok: false, json: async () => ({}) }),
};
vm.createContext(context);
vm.runInContext(fs.readFileSync(scriptPath, "utf8"), context);
vm.runInContext(`leadyState.activeScope = ${JSON.stringify(scope)}; leadyRenderRows(${itemsJson});`, context);
process.stdout.write(JSON.stringify(list.children.map((card) => card.innerHTML)));
"""


def _render(tmp_path, items, scope):
    node = shutil.which("node")
    if not node:
        pytest.skip("node is not available")
    harness = tmp_path / "render.js"
    harness.write_text(_NODE_HARNESS, encoding="utf-8")
    script = REPO_ROOT / "InvestmentManager" / "static" / "js" / "leady_logs.js"
    completed = subprocess.run([node, str(harness), str(script), json.dumps(items), scope],
                               capture_output=True, text=True, encoding="utf-8", timeout=60)
    assert completed.returncode == 0, completed.stderr
    return json.loads(completed.stdout)


MALICIOUS_ITEM = {
    "id": 1, "log_type": "leads", "created_at": XSS, "platform": XSS, "event": XSS, "status": XSS,
    "offer_url": XSS, "email": XSS, "phone_message": XSS, "ip": XSS, "path": XSS,
    "inbox_id": 3, "inbox_status": XSS, "assigned_agent_id": XSS, "crm_lead_id": XSS,
    "inbox_notes": XSS + "x" * 100, "payload": {},
}


@pytest.mark.parametrize("scope", ["leads", "non_leads"])
def test_panel_escapes_every_untrusted_field(tmp_path, scope):
    item = dict(MALICIOUS_ITEM, log_type="leads" if scope == "leads" else "phone_views")
    [html] = _render(tmp_path, [item], scope)

    assert "<img" not in html
    assert 'title=""' not in html  # no attribute breakout
    assert "&lt;img src=x onerror=alert(document.domain)&gt;" in html
    assert "&quot;&gt;&lt;img" in html


def test_panel_renders_normal_lead_values_readably(tmp_path):
    item = {
        "id": 2, "log_type": "leads", "created_at": "2026-10-19T10:00:00", "platform": "tripinvest",
        "event": "", "status": "sent", "offer_url": "https://tripinvest.pl/oferta/a-1?x=1&y=2",
        "email": "jan@example.com", "phone_message": "Dzień dobry,\nproszę o kontakt.",
        "ip": "203.0.113.5", "path": "/api/platform_send_lead", "payload": {},
        "inbox_id": None, "inbox_status": "", "assigned_agent_id": None, "crm_lead_id": None, "inbox_notes": "",
    }
    [html] = _render(tmp_path, [item], "leads")

    assert "TripInvest" in html and "Wysłano" in html
    assert "jan@example.com" in html
    assert "Dzień dobry,\nproszę o kontakt." in html
    assert "203.0.113.5" in html
    assert 'title="https://tripinvest.pl/oferta/a-1?x=1&amp;y=2"' in html  # & escaped, link text intact
