"""Tiny node:vm harness for the CRM front end: runs the REAL static scripts against a recording DOM stub (same approach as
test_knowledge_center_xss.py). A test supplies the scripts to load and a JS snippet; the snippet's result plus every `innerHTML`
write and every `textContent` write are returned, so a test can assert that a payload was shown as TEXT and never parsed as HTML.
Skipped when node is not available. Nothing is rendered in a browser and nothing leaves the process.
"""
import json
import shutil
import subprocess
from pathlib import Path

import pytest

JS_DIR = Path(__file__).resolve().parents[2] / 'InvestmentManager' / 'static' / 'js'

IMG = '<img src=x onerror=window.__xss=1>'
ATTR = '" onmouseover="window.__xss=1" x="'
JS_URL = 'javascript:window.__xss=1'

_HARNESS = r"""
const fs = require('fs'), vm = require('vm'), path = require('path');
const [, , jsDir, specJson] = process.argv;
const spec = JSON.parse(specJson);
const htmlWrites = [], textWrites = [];
const byId = {}, handlers = {}, fetchLog = [];

function el(tag) {
  const t = Object.assign(function () {}, { tag, children: [], dataset: {}, style: {}, listeners: {}, attrs: {}, _html: '', _text: '' });
  const p = new Proxy(t, {
    get(o, k) {
      if (k === 'innerHTML') return o._html;
      if (k === 'textContent' || k === 'value') return o._text;
      if (k === 'children' || k === 'dataset' || k === 'style' || k === 'attrs' || k === 'listeners') return o[k];
      if (k === 'classList') return { add() {}, remove() {}, toggle() {}, contains() { return false; } };
      if (k === 'appendChild' || k === 'append' || k === 'prepend') return (...cs) => { cs.forEach((c) => o.children.push(c)); return cs[0]; };
      if (k === 'addEventListener') return (type, fn) => { (o.listeners[type] = o.listeners[type] || []).push(fn); };
      if (k === 'setAttribute') return (n, v) => { o.attrs[n] = String(v); };
      if (k === 'getAttribute') return (n) => (n in o.attrs ? o.attrs[n] : null);
      if (k === 'querySelector' || k === 'closest') return (sel) => { const found = (o._found = o._found || {}); return (found[sel] = found[sel] || el('found')); };
      if (k === 'querySelectorAll') return () => [];
      if (k === 'getBoundingClientRect') return () => ({ left: 0, top: 0, width: 0, height: 0, bottom: 0, right: 0 });
      if (k === Symbol.toPrimitive) return () => '';
      if (k in o) return o[k];
      return typeof k === 'string' ? function () { return p; } : undefined;
    },
    set(o, k, v) {
      if (k === 'innerHTML') { o._html = String(v); htmlWrites.push({ tag: o.tag, html: String(v) }); if (v === '') o.children.length = 0; return true; }
      if (k === 'textContent' || k === 'value') { o._text = String(v); textWrites.push({ tag: o.tag, text: String(v) }); return true; }
      o[k] = v; return true;
    },
  });
  return p;
}
const document = {
  readyState: 'complete', body: el('body'), head: el('head'),
  getElementById: (id) => (byId[id] = byId[id] || el('div#' + id)),
  createElement: (tag) => el(tag), createTextNode: (text) => { const n = el('#text'); n.textContent = text; return n; },
  querySelector: () => el('found'), querySelectorAll: () => [], createDocumentFragment: () => el('fragment'),
  addEventListener: (type, fn) => { (handlers[type] = handlers[type] || []).push(fn); },
};
const context = {
  console: { log() {}, error() {}, warn() {}, info() {} }, JSON, Date, Number, String, Math, Array, Object, Promise, Set, Map, RegExp, Symbol, Boolean, Error,
  parseInt, parseFloat, isNaN, encodeURIComponent, decodeURIComponent, URL, URLSearchParams, Intl,
  setTimeout: () => 0, clearTimeout() {}, setInterval: () => 0, clearInterval() {}, requestAnimationFrame: () => 0,
  document, confirm: () => true, alert() {}, prompt: () => null,
  localStorage: { getItem: () => null, setItem() {}, removeItem() {} }, sessionStorage: { getItem: () => null, setItem() {}, removeItem() {} },
  fetch: (url, opts) => { fetchLog.push(String(url)); const r = spec.fetch && spec.fetch[String(url)]; return r === undefined ? new Promise(() => {}) : Promise.resolve({ ok: true, json: () => Promise.resolve(r), text: () => Promise.resolve(typeof r === 'string' ? r : JSON.stringify(r)) }); },
  Chart: function () { return { destroy() {}, update() {}, data: {}, options: {} }; },
};
context.window = context;
context.location = { href: 'http://localhost/crm/', origin: 'http://localhost', search: '', pathname: '/crm/', hash: '' };
vm.createContext(context);
(spec.scripts || []).forEach((file) => vm.runInContext(fs.readFileSync(path.join(jsDir, file), 'utf8'), context, { filename: file }));
(async () => {
  const result = await vm.runInContext('(async () => {' + spec.code + '})()', context);
  for (let i = 0; i < 15; i++) await new Promise((r) => setImmediate(r));
  process.stdout.write(JSON.stringify({ result, htmlWrites, textWrites, fetchLog, handlers: Object.keys(handlers) }));
})().catch((e) => { process.stderr.write(String(e && e.stack || e)); process.exit(1); });
"""


def run_js(tmp_path, scripts, code, fetch=None):
    node = shutil.which('node')
    if not node:
        pytest.skip('node is not available')
    harness = Path(tmp_path) / 'dom_harness.js'
    harness.write_text(_HARNESS, encoding='utf-8')
    spec = json.dumps({'scripts': ['html_utils.js', *scripts], 'code': code, 'fetch': fetch or {}})
    completed = subprocess.run([node, str(harness), str(JS_DIR), spec], capture_output=True, text=True, encoding='utf-8', timeout=90)
    assert completed.returncode == 0, completed.stderr
    return json.loads(completed.stdout)


def raw_html(result):
    """All HTML the scripts handed to the parser (innerHTML writes), as one string."""
    return '\n'.join(write['html'] for write in result['htmlWrites'])


def shown_text(result):
    return '\n'.join(write['text'] for write in result['textWrites'])
