"""INV-FIX-002 / INV-AUD-008: knowledge center notes and comments cannot inject HTML.

Runs the real knowledge_center.js in node:vm with a minimal DOM stub (skipped
without node): renders notes and a comment thread, then triggers the edit /
delete / comment handlers to show they still receive the original data.
"""
import json
import shutil
import subprocess
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = REPO_ROOT / "InvestmentManager" / "static" / "js" / "knowledge_center.js"
XSS = "<img src=x onerror=alert(document.domain)>"
ATTR_BREAKOUT = "') onmouseover=alert(1) x=('"

_HARNESS = r"""
const fs = require("fs");
const vm = require("vm");
const [, , scriptPath, inputJson] = process.argv;
const input = JSON.parse(inputJson);

function element(tag) {
  const el = {
    tag, children: [], className: "", innerHTML: "", textContent: "", value: "", listeners: {},
    dataset: {}, classList: { add() {}, remove() {}, contains() { return false; } },
    appendChild(child) { this.children.push(child); return child; },
    addEventListener(type, fn) { (this.listeners[type] = this.listeners[type] || []).push(fn); },
    _found: {},
    querySelector(selector) {
      // Present only when the rendered HTML contains the attribute the selector asks for.
      const m = selector.match(/^\[([\w-]+)="([^"]+)"\]$/);
      if (!m || !this.innerHTML.includes(`${m[1]}="${m[2]}"`)) return null;
      return (this._found[selector] = this._found[selector] || element("found"));
    },
    closest() { return null; },
    scrollTo() {},
  };
  return el;
}

const containers = { notes: element("div") };
const calls = [];
const context = {
  console, JSON, Date, Number, String, parseInt, encodeURIComponent,
  setTimeout: () => 0,
  document: {
    readyState: "complete",
    getElementById: (id) => containers[id] || null,
    createElement: element,
    addEventListener() {},
    body: { dataset: { userId: String(input.userId) } },
  },
  fetch: () => new Promise(() => {}),
  confirm: () => true,
  alert() {},
};
vm.createContext(context);
vm.runInContext(fs.readFileSync(scriptPath, "utf8"), context);
// Record handler targets instead of opening modals / calling the API.
context.openNoteModal = (note) => calls.push(["edit", note]);
context.deleteNote = (ts, priv) => calls.push(["delete", ts, priv]);
context.submitInlineComment = (event, ts) => calls.push(["comment", ts]);

vm.runInContext(`renderNotes("notes", ${JSON.stringify(input.notes)}, ${input.userId}, [], [])`, context);
const noteCards = containers.notes.children.map((card) => card);
noteCards.forEach((card) => {
  const edit = card._found['[data-note-action="edit"]'];
  const del = card._found['[data-note-action="delete"]'];
  if (edit) edit.listeners.click.forEach((fn) => fn());
  if (del) del.listeners.click.forEach((fn) => fn());
});

const thread = element("div");
context.__thread = thread;
vm.runInContext(`renderCommentThread(__thread, ${JSON.stringify(input.comments)}, ${JSON.stringify(input.timestamp)})`, context);
const form = thread._found['[data-comment-form="1"]'];
if (form) form.listeners.submit.forEach((fn) => fn({ preventDefault() {} }));

process.stdout.write(JSON.stringify({
  notes: noteCards.map((card) => card.innerHTML),
  thread: thread.innerHTML,
  calls,
}));
"""


def _run(tmp_path, notes, comments, *, user_id=7, timestamp="2026-10-19T10:00:00.123456"):
    node = shutil.which("node")
    if not node:
        pytest.skip("node is not available")
    harness = tmp_path / "kc.js"
    harness.write_text(_HARNESS, encoding="utf-8")
    payload = json.dumps({"notes": notes, "comments": comments, "userId": user_id, "timestamp": timestamp})
    completed = subprocess.run([node, str(harness), str(SCRIPT), payload],
                               capture_output=True, text=True, encoding="utf-8", timeout=60)
    assert completed.returncode == 0, completed.stderr
    return json.loads(completed.stdout)


def _note(**values):
    note = {"title": "Tytuł", "content": "Treść", "timestamp": "2026-10-19T10:00:00.123456",
            "author_id": 7, "author_name": "Jan Kowalski", "private": False, "comments": []}
    note.update(values)
    return note


def test_malicious_note_and_comment_fields_are_escaped(tmp_path):
    notes = [_note(title=XSS + ATTR_BREAKOUT, content=XSS, author_name=XSS)]
    comments = [{"comment": XSS, "author_name": XSS + ATTR_BREAKOUT, "author_id": 9,
                 "timestamp": "2026-10-19T11:00:00"}]

    result = _run(tmp_path, notes, comments)

    for html in [*result["notes"], result["thread"]]:
        assert "<img" not in html
        assert "&lt;img src=x onerror=alert(document.domain)&gt;" in html
        assert "onclick=" not in html and "onsubmit=" not in html  # no data inside handler attributes
    assert "&#39;) onmouseover=alert(1) x=(&#39;" in result["notes"][0]


def test_edit_delete_and_comment_handlers_receive_the_original_data(tmp_path):
    note = _note(title=ATTR_BREAKOUT, private=True)
    result = _run(tmp_path, [note], [], timestamp=note["timestamp"])

    assert result["calls"] == [
        ["edit", note],
        ["delete", note["timestamp"], True],
        ["comment", note["timestamp"]],
    ]


def test_foreign_note_has_no_edit_or_delete_buttons(tmp_path):
    result = _run(tmp_path, [_note(author_id=8)], [])

    assert "data-note-action" not in result["notes"][0]
    assert [c[0] for c in result["calls"]] == ["comment"]


def test_polish_and_multiline_text_is_kept_readable(tmp_path):
    content = "Zażółć gęślą jaźń.\nDruga linia\n\n• punkt"
    notes = [_note(title="Spotkanie: ŁÓDŹ & Gdańsk", content=content, author_name="Paweł Żółtek")]
    comments = [{"comment": "Dziękuję!\nDo zobaczenia.", "author_name": "Ślązak", "author_id": 7,
                 "timestamp": "2026-10-19T11:00:00"}]

    result = _run(tmp_path, notes, comments)

    html = result["notes"][0]
    assert "Spotkanie: ŁÓDŹ &amp; Gdańsk" in html
    assert f'whitespace-pre-line">{content}</p>' in html
    assert "Paweł Żółtek" in html
    assert "Dziękuję!\nDo zobaczenia." in result["thread"]
    assert "Ślązak" in result["thread"]
    assert "comment-wrapper user" in result["thread"]  # own comment styling kept
    assert "💬 0 komentarzy" in html
