import json
import shutil
import subprocess
from pathlib import Path

import pytest
from flask import render_template


ROOT = Path(__file__).resolve().parents[2]
CONSENT_JS = ROOT / "InvestmentWebsite/static/js/analytics/privacy_consent.js"
NODE = shutil.which("node")


NODE_HARNESS = r"""
const fs = require("fs");
const vm = require("vm");
const source = fs.readFileSync(process.argv[1], "utf8");
const scenario = JSON.parse(process.argv[2]);
const consentKey = "investment_analytics_consent_v1";
const storage = new Map(Object.entries(scenario.storage || {}));
const dispatched = [];

function element() {
  return {
    textContent: "",
    hidden: false,
    dataset: {},
    listeners: {},
    addEventListener(type, callback) { this.listeners[type] = callback; },
    focus(options) { this.focusOptions = options || {}; },
  };
}

const title = element();
const description = element();
const noticeTitle = element();
const noticePl = element();
const noticeEn = element();
const accept = element();
const reject = element();
const error = element();
error.hidden = true;
const manage = element();
const banner = element();
banner.hidden = true;
banner.querySelector = (selector) => ({
  "[data-consent-title]": title,
  "[data-consent-description]": description,
  "[data-consent-notice-title]": noticeTitle,
  '[data-consent-notice="pl"]': noticePl,
  '[data-consent-notice="en"]': noticeEn,
  '[data-consent-choice="accepted"]': accept,
  '[data-consent-choice="rejected"]': reject,
  "[data-consent-error]": error,
})[selector] || null;

const documentListeners = {};
const document = {
  documentElement: {lang: scenario.lang || "pl"},
  getElementById(id) {
    if (id === "investment-analytics-consent") return banner;
    if (id === "investment-analytics-consent-manage") return manage;
    return null;
  },
  addEventListener(type, callback) { documentListeners[type] = callback; },
};
const window = {
  location: {pathname: scenario.pathname || "/", search: scenario.search || ""},
  localStorage: {
    getItem(key) {
      if (scenario.storageFailure) throw new Error("storage blocked");
      return storage.has(key) ? storage.get(key) : null;
    },
    setItem(key, value) {
      if (scenario.storageFailure) throw new Error("storage blocked");
      storage.set(key, String(value));
    },
  },
  dispatchEvent(event) { dispatched.push({type: event.type, detail: event.detail}); },
};
class CustomEvent {
  constructor(type, options) { this.type = type; this.detail = options.detail; }
}

vm.runInNewContext(source, {document, window, URLSearchParams, CustomEvent}, {filename: process.argv[1]});
for (const action of scenario.actions || []) {
  if (action === "manage") manage.listeners.click();
  if (action === "accept") accept.listeners.click();
  if (action === "reject") reject.listeners.click();
}
process.stdout.write(JSON.stringify({
  bannerHidden: banner.hidden,
  errorHidden: error.hidden,
  title: title.textContent,
  description: description.textContent,
  noticeTitle: noticeTitle.textContent,
  noticePlHidden: noticePl.hidden,
  noticeEnHidden: noticeEn.hidden,
  accept: accept.textContent,
  reject: reject.textContent,
  manage: manage.textContent,
  decision: storage.get(consentKey) || null,
  acceptFocus: accept.focusOptions || null,
  manageFocus: manage.focusOptions || null,
  dispatched,
}));
"""


def _run_ui(scenario):
    if NODE is None:
        pytest.skip("Node is required for the privacy consent UI test")
    completed = subprocess.run(
        [NODE, "-e", NODE_HARNESS, str(CONSENT_JS), json.dumps(scenario)],
        capture_output=True,
        text=True,
        encoding="utf-8",
        check=True,
        timeout=30,
    )
    return json.loads(completed.stdout)


def test_first_polish_visit_shows_equal_accept_and_reject_choices():
    result = _run_ui({"lang": "pl", "storage": {}})

    assert result["bannerHidden"] is False
    assert result["accept"] == "Akceptuję"
    assert result["reject"] == "Odrzucam"
    assert result["manage"] == "Prywatność i analityka"
    assert result["noticeTitle"] == "Informacja o analityce"
    assert result["noticePlHidden"] is False
    assert result["noticeEnHidden"] is True
    assert "bez cookies analitycznych" in result["description"]
    assert "własnego systemu analitycznego" in result["description"]
    assert "Matomo" not in result["description"]
    assert "wycofać w stopce" in result["description"]
    assert result["decision"] is None
    assert result["dispatched"] == []


@pytest.mark.parametrize(
    "scenario",
    [
        {"lang": "en", "storage": {}},
        {"lang": "pl", "pathname": "/nieruchomosci/hiszpania/lanzarote/offer/x", "storage": {}},
        {"lang": "pl", "search": "?lang=en", "storage": {}},
    ],
)
def test_english_public_variants_show_english_consent_copy(scenario):
    result = _run_ui(scenario)

    assert result["accept"] == "Accept"
    assert result["reject"] == "Reject"
    assert result["manage"] == "Privacy and analytics"
    assert result["noticeTitle"] == "Analytics privacy information"
    assert result["noticeEnHidden"] is False
    assert result["noticePlHidden"] is True
    assert "without analytics cookies" in result["description"]
    assert "our own analytics system" in result["description"]
    assert "Matomo" not in result["description"]
    assert "withdraw consent in the footer" in result["description"]


@pytest.mark.parametrize(("action", "decision"), [("accept", "accepted"), ("reject", "rejected")])
def test_first_choice_closes_banner_without_moving_focus_to_the_footer(action, decision):
    result = _run_ui({"actions": [action]})

    assert result["decision"] == decision
    assert result["bannerHidden"] is True
    assert result["manageFocus"] is None
    assert result["dispatched"] == [{
        "type": "investment:analytics-consent-changed",
        "detail": decision,
    }]


def test_footer_control_changes_accepted_decision_to_rejected_in_same_visit():
    result = _run_ui({
        "lang": "pl",
        "storage": {"investment_analytics_consent_v1": "accepted"},
        "actions": ["manage", "reject"],
    })

    assert result["decision"] == "rejected"
    assert result["bannerHidden"] is True
    assert result["acceptFocus"] == {"preventScroll": True}
    assert result["manageFocus"] == {"preventScroll": True}
    assert result["dispatched"] == [{
        "type": "investment:analytics-consent-changed",
        "detail": "rejected",
    }]


def test_storage_failure_keeps_analytics_off_and_banner_open():
    result = _run_ui({"lang": "en", "storage": {}, "storageFailure": True, "actions": ["accept"]})

    assert result["decision"] is None
    assert result["bannerHidden"] is False
    assert result["errorHidden"] is False
    assert result["dispatched"] == []


def test_consent_ui_renders_only_when_matomo_is_explicitly_enabled(app):
    with app.test_request_context("/"):
        app.config["MATOMO_ENABLED"] = False
        disabled = render_template("components/footer.html")
        app.config["MATOMO_ENABLED"] = True
        enabled = render_template("components/footer.html")

    assert "investment-analytics-consent" not in disabled
    assert enabled.count('id="investment-analytics-consent"') == 1
    assert enabled.count('id="investment-analytics-consent-manage"') == 1
    assert enabled.count("/static/js/analytics/privacy_consent.js") == 1


def test_analytics_notice_is_available_inside_the_banner_before_either_choice(app):
    app.config["MATOMO_ENABLED"] = True
    with app.test_request_context("/"):
        html = render_template("components/privacy_consent.html")

    notice_start = html.index('<details class="investment-consent__notice">')
    notice_end = html.index("</details>", notice_start)
    notice = html[notice_start:notice_end]
    assert notice_end < html.index('data-consent-choice="accepted"')
    assert notice_end < html.index('data-consent-choice="rejected"')
    assert 'data-consent-notice="pl" lang="pl"' in notice
    assert 'data-consent-notice="en" lang="en"' in notice
    assert notice.count("180 dni") == notice.count("180 days") == 1
    assert notice.count("INVESTMENT NIERUCHOMOŚCI Sebastian SZYMONIAK") == 2
    assert notice.count('href="mailto:sebastian.szymoniak@investment-nieruchomosci.com"') == 2
    assert "art. 6 ust. 1 lit. a RODO" in notice
    assert "Article 6(1)(a) GDPR" in notice
    assert "własnego systemu analitycznego" in notice
    assert "our own analytics system" in notice
    assert "Matomo" not in notice
    assert "/polityka-prywatnosci" not in notice
    assert "/privacy-policy" not in notice


def test_crm_and_error_pages_do_not_render_consent_ui(app):
    app.config["MATOMO_ENABLED"] = True
    client = app.test_client()

    assert "investment-analytics-consent" not in client.get("/crm/").get_data(as_text=True)
    error = client.get("/stage6b-deliberate-404")
    assert error.status_code == 404
    assert "investment-analytics-consent" not in error.get_data(as_text=True)


def test_enabled_public_form_page_renders_one_consent_ui_and_local_assets_without_session_cookie(app):
    app.config["MATOMO_ENABLED"] = True
    client = app.test_client()

    response = client.get("/nieruchomosci/cypr")
    html = response.get_data(as_text=True)

    assert response.status_code == 200
    assert html.count('id="investment-analytics-consent"') == 1
    assert html.count('id="investment-analytics-consent-manage"') == 1
    assert html.count("/static/css/privacy_consent.css") == 1
    assert html.count("/static/js/analytics/privacy_consent.js") == 1
    assert not any(value.lower().startswith("session=") for value in response.headers.getlist("Set-Cookie"))
    assert client.get("/static/css/privacy_consent.css").status_code == 200
    assert client.get("/static/js/analytics/privacy_consent.js").status_code == 200


def test_no_optout_widget_or_cookie_api_is_used():
    combined = (
        CONSENT_JS.read_text(encoding="utf-8")
        + (ROOT / "InvestmentWebsite/static/js/analytics/matomo.js").read_text(encoding="utf-8")
    )
    assert "optOutJS" not in combined
    assert "document.cookie" not in combined
