"""CRM offer file-operation security boundary (Wave A3).

Every document/image mutation route joins a client-supplied name under an
offer directory. These tests confirm the boundary: legitimate names work,
traversal/absolute/nested/cross-offer names are rejected with a 4xx, and a
sentinel file placed outside the offer directory stays byte-identical and no
file is created outside it.

All runtime lives under a temporary DATA_DIR; the developer's real
InvestmentData is never touched.
"""
import hashlib
import io
import sqlite3

import pytest
from PIL import Image

from modules.core import file_safety

OFFER_ID = 7
OTHER_OFFER_ID = 8


def _sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None


def _write_jpg(path, color):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", (40, 30), color).save(path, "JPEG")


@pytest.fixture()
def offer_runtime(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    (tmp_path / "databases").mkdir()
    sqlite3.connect(tmp_path / "databases" / "IDB.db").close()

    offers = tmp_path / "offers"
    o7 = offers / str(OFFER_ID)
    o8 = offers / str(OTHER_OFFER_ID)
    _write_jpg(o7 / f"image_{OFFER_ID}_url_0.jpg", "red")
    _write_jpg(o7 / f"image_{OFFER_ID}_url_1.jpg", "blue")
    _write_jpg(o8 / f"image_{OTHER_OFFER_ID}_url_0.jpg", "green")
    (o7 / "docs").mkdir(parents=True)
    (o7 / "docs" / "existing.pdf").write_bytes(b"offer-7-doc")
    (o8 / "docs").mkdir(parents=True)
    (o8 / "docs" / "umowa8.pdf").write_bytes(b"offer-8-doc")

    # Sentinels OUTSIDE any offer directory.
    (tmp_path / "SENTINEL_secret.txt").write_text("TOP-SECRET", encoding="utf-8")
    _write_jpg(tmp_path / "SENTINEL_outside.jpg", "yellow")

    return {
        "root": tmp_path,
        "o7": o7,
        "o8": o8,
        "secret": tmp_path / "SENTINEL_secret.txt",
        "outside_img": tmp_path / "SENTINEL_outside.jpg",
    }


# INV-SEC-001: domestic offer routes are owner-scoped; these file/storage tests use
# offers without an EstateData owner row, so they run as master (unchanged handler path).
def _login(client, access_level="master"):
    with client.session_transaction() as sess:
        sess["user_id"] = 2
        sess["access_level"] = access_level
        sess["first_name"] = "Test"
        sess["last_name"] = "User"


def _outside_files(root):
    """Files directly under DATA_DIR that are not part of the seeded layout."""
    seeded = {"SENTINEL_secret.txt", "SENTINEL_outside.jpg"}
    return sorted(p.name for p in root.iterdir() if p.is_file() and p.name not in seeded)


# Names that must never denote a file outside the offer/docs directory.
TRAVERSAL_NAMES = [
    "../evil.txt",
    "..\\evil.txt",
    "../../SENTINEL_secret.txt",
    "..\\..\\SENTINEL_secret.txt",
    "/etc/passwd",
    "C:\\Windows\\win.ini",
    "sub/dir/evil.txt",
    "../8/docs/umowa8.pdf",
    "..",
    ".",
]


# ---------------------------------------------------------------------------
# Document upload
# ---------------------------------------------------------------------------

class TestDocumentUpload:
    @pytest.mark.parametrize("name", ["Umowa najmu.pdf", "Zażółć gęślą jaźń.pdf", "raport (2026).xlsx"])
    def test_legitimate_names_succeed_and_stay_in_docs(self, client, offer_runtime, name):
        _login(client)
        resp = client.post(
            f"/crm/offers/documents/{OFFER_ID}",
            data={"file": (io.BytesIO(b"content"), name)},
            content_type="multipart/form-data",
        )
        assert resp.status_code == 200
        assert (offer_runtime["o7"] / "docs" / name).is_file()
        assert _outside_files(offer_runtime["root"]) == []

    def test_duplicate_name_prompts_then_overwrites_on_force(self, client, offer_runtime):
        _login(client)
        first = client.post(
            f"/crm/offers/documents/{OFFER_ID}",
            data={"file": (io.BytesIO(b"v1"), "existing.pdf")},
            content_type="multipart/form-data",
        )
        assert first.get_json() == {"exists": True, "filename": "existing.pdf"}
        assert (offer_runtime["o7"] / "docs" / "existing.pdf").read_bytes() == b"offer-7-doc"

        forced = client.post(
            f"/crm/offers/documents/{OFFER_ID}?force=true",
            data={"file": (io.BytesIO(b"v2"), "existing.pdf")},
            content_type="multipart/form-data",
        )
        assert forced.get_json()["overwritten"] is True
        assert (offer_runtime["o7"] / "docs" / "existing.pdf").read_bytes() == b"v2"

    @pytest.mark.parametrize("name", TRAVERSAL_NAMES + ["/abs/WRITTEN.txt"])
    def test_traversal_upload_is_rejected_and_writes_nothing_outside(self, client, offer_runtime, name):
        _login(client)
        root, docs = offer_runtime["root"], offer_runtime["o7"] / "docs"
        before_o8 = _sha(offer_runtime["o8"] / "docs" / "umowa8.pdf")
        resp = client.post(
            f"/crm/offers/documents/{OFFER_ID}",
            data={"file": (io.BytesIO(b"PWNED"), name)},
            content_type="multipart/form-data",
        )
        # Werkzeug 3.1.8 keeps a backslash inside a quoted multipart filename (the validator answers 400);
        # 3.1.9 strips it, so the server only ever sees the last component and may store it safely (200).
        # Any other name must always be refused.
        backslash_only = "\\" in name and "/" not in name and ":" not in name
        if backslash_only:
            assert resp.status_code in (200, 400)
        else:
            assert resp.status_code == 400
        # Invariants in every case: nothing outside the offer's docs directory, sentinels and other offers untouched.
        assert _outside_files(root) == []
        assert offer_runtime["secret"].read_text(encoding="utf-8") == "TOP-SECRET"
        assert _sha(offer_runtime["o8"] / "docs" / "umowa8.pdf") == before_o8
        assert not (offer_runtime["o7"] / "evil.txt").exists()
        new_files = sorted(p.name for p in docs.iterdir() if p.name != "existing.pdf")
        assert (docs / "existing.pdf").read_bytes() == b"offer-7-doc"
        if resp.status_code == 400:
            assert new_files == []
        else:
            # at most one new file: a plain single-component name directly inside docs/
            assert len(new_files) == 1
            stored = new_files[0]
            # 3.1.9 drops the backslashes ("..\\evil.txt" -> "..evil.txt"): still one inert component inside docs/
            assert stored == name.replace("\\", "")
            assert not any(sep in stored for sep in ("/", "\\", ":")) and stored not in ("", ".", "..") and not stored.startswith("./")
            assert (docs / stored).resolve().parent == docs.resolve()
            assert (docs / stored).read_bytes() == b"PWNED"


class TestValidateDocumentFilename:
    """The production validator itself, independent of the Werkzeug version that parses the multipart header."""

    @pytest.mark.parametrize("name", [
        "..\\evil.txt", "..\\..\\SENTINEL_secret.txt", "sub\\evil.txt", "evil.txt\\",
        "../evil.txt", "../../SENTINEL_secret.txt", "sub/dir/evil.txt", "../8/docs/umowa8.pdf",
        "/etc/passwd", "/abs/WRITTEN.txt", "\\\\server\\share\\x.txt",
        "C:\\Windows\\win.ini", "C:evil.txt", "c:/windows/win.ini", "D:\\x.pdf",
        "..", ".", "", "   ", "a\x00b.txt", "a\nb.txt",
    ])
    def test_unsafe_names_are_rejected(self, name):
        with pytest.raises(Exception):
            file_safety.validate_document_filename(name)

    @pytest.mark.parametrize("name", ["Umowa najmu.pdf", "Zażółć gęślą jaźń.pdf", "raport (2026).xlsx", "a.b.c.txt"])
    def test_plain_names_are_accepted_unchanged(self, name):
        assert file_safety.validate_document_filename(name) == name

    def test_non_string_is_rejected(self):
        with pytest.raises(Exception):
            file_safety.validate_document_filename(None)


# ---------------------------------------------------------------------------
# Document delete
# ---------------------------------------------------------------------------

class TestDocumentDelete:
    def test_legitimate_delete_succeeds(self, client, offer_runtime):
        _login(client)
        resp = client.post(f"/crm/offers/documents/{OFFER_ID}/delete", json={"filename": "existing.pdf"})
        assert resp.status_code == 200
        assert not (offer_runtime["o7"] / "docs" / "existing.pdf").exists()

    @pytest.mark.parametrize("name", TRAVERSAL_NAMES)
    def test_traversal_delete_is_rejected_and_sentinels_unchanged(self, client, offer_runtime, name):
        _login(client)
        secret_before = _sha(offer_runtime["secret"])
        other_doc_before = _sha(offer_runtime["o8"] / "docs" / "umowa8.pdf")

        resp = client.post(f"/crm/offers/documents/{OFFER_ID}/delete", json={"filename": name})

        assert resp.status_code == 400
        assert _sha(offer_runtime["secret"]) == secret_before
        assert _sha(offer_runtime["o8"] / "docs" / "umowa8.pdf") == other_doc_before


# ---------------------------------------------------------------------------
# Document download / serve
# ---------------------------------------------------------------------------

class TestDocumentDownload:
    def test_legitimate_download_returns_content(self, client, offer_runtime):
        _login(client)
        resp = client.get(f"/crm/offers/documents/{OFFER_ID}/file/existing.pdf")
        assert resp.status_code == 200
        assert resp.data == b"offer-7-doc"

    @pytest.mark.parametrize(
        "encoded",
        ["..%2F..%2FSENTINEL_secret.txt", "..%5C..%5CSENTINEL_secret.txt", "..%2F..%2F8%2Fdocs%2Fumowa8.pdf"],
    )
    def test_encoded_traversal_download_does_not_leak(self, client, offer_runtime, encoded):
        _login(client)
        resp = client.get(f"/crm/offers/documents/{OFFER_ID}/file/{encoded}")
        assert resp.status_code == 404
        assert b"TOP-SECRET" not in resp.data
        assert b"offer-8-doc" not in resp.data


# ---------------------------------------------------------------------------
# Image delete / set-main / label -- server grammar only
# ---------------------------------------------------------------------------

BAD_IMAGE_NAMES = [
    "image_8_url_0.jpg",            # wrong offer id
    "image_7_url_0.gif",           # bad extension
    "notes.md",                     # not an image name
    "../image_7_url_0.jpg",        # traversal
    "..\\image_7_url_0.jpg",       # windows traversal
    "../../SENTINEL_secret.txt",   # escape to sentinel
    "../8/image_8_url_0.jpg",      # cross-offer
    "image_7_url_0.jpg; DROP",     # trailing junk
    "",
]


class TestImageDelete:
    def test_legitimate_delete_succeeds(self, client, offer_runtime):
        _login(client)
        resp = client.post(f"/crm/offers/images/{OFFER_ID}/delete", json={"filename": f"image_{OFFER_ID}_url_1.jpg"})
        assert resp.status_code == 200
        assert not (offer_runtime["o7"] / f"image_{OFFER_ID}_url_1.jpg").exists()

    @pytest.mark.parametrize("name", BAD_IMAGE_NAMES)
    def test_bad_names_rejected_and_other_offer_untouched(self, client, offer_runtime, name):
        _login(client)
        secret_before = _sha(offer_runtime["secret"])
        o8_before = _sha(offer_runtime["o8"] / f"image_{OTHER_OFFER_ID}_url_0.jpg")

        resp = client.post(f"/crm/offers/images/{OFFER_ID}/delete", json={"filename": name})

        assert resp.status_code == 400
        assert _sha(offer_runtime["secret"]) == secret_before
        assert _sha(offer_runtime["o8"] / f"image_{OTHER_OFFER_ID}_url_0.jpg") == o8_before


class TestSetMainImage:
    def test_legitimate_set_main_swaps(self, client, offer_runtime):
        _login(client)
        url0_before = _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_0.jpg")
        url1_before = _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_1.jpg")
        resp = client.post(f"/crm/offers/images/{OFFER_ID}/set-main", json={"filename": f"image_{OFFER_ID}_url_1.jpg"})
        assert resp.status_code == 200
        assert _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_0.jpg") == url1_before
        assert _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_1.jpg") == url0_before

    @pytest.mark.parametrize("name", BAD_IMAGE_NAMES)
    def test_bad_names_rejected(self, client, offer_runtime, name):
        _login(client)
        secret_before = _sha(offer_runtime["secret"])
        url0_before = _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_0.jpg")

        resp = client.post(f"/crm/offers/images/{OFFER_ID}/set-main", json={"filename": name})

        assert resp.status_code == 400
        assert _sha(offer_runtime["secret"]) == secret_before
        assert _sha(offer_runtime["o7"] / f"image_{OFFER_ID}_url_0.jpg") == url0_before

    def test_public_media_route_cannot_serve_out_of_tree_file_after_attempted_set_main(self, client, offer_runtime):
        _login(client)
        client.post(f"/crm/offers/images/{OFFER_ID}/set-main", json={"filename": "../../SENTINEL_secret.txt"})

        # url_0 must still be the original in-tree image, and the public
        # media route must not serve the sentinel content.
        assert b"TOP-SECRET" not in (offer_runtime["o7"] / f"image_{OFFER_ID}_url_0.jpg").read_bytes()
        public = client.get(f"/static/images/{OFFER_ID}/image_{OFFER_ID}_url_0.jpg")
        assert public.status_code == 200
        assert b"TOP-SECRET" not in public.data


class TestLabelImage:
    def test_legitimate_label_succeeds(self, client, offer_runtime, monkeypatch):
        _login(client)
        resp = client.post(
            f"/crm/offers/images/{OFFER_ID}/label",
            json={"filename": f"image_{OFFER_ID}_url_0.jpg", "label": "SPRZEDANE"},
        )
        assert resp.status_code == 200

    @pytest.mark.parametrize("name", BAD_IMAGE_NAMES)
    def test_bad_names_rejected_and_outside_image_untouched(self, client, offer_runtime, name):
        _login(client)
        outside_before = _sha(offer_runtime["outside_img"])

        resp = client.post(f"/crm/offers/images/{OFFER_ID}/label", json={"filename": name, "label": "X"})

        assert resp.status_code == 400
        assert _sha(offer_runtime["outside_img"]) == outside_before


# ---------------------------------------------------------------------------
# Error hygiene
# ---------------------------------------------------------------------------

def test_rejection_message_does_not_leak_filesystem_paths(client, offer_runtime):
    _login(client)
    resp = client.post(f"/crm/offers/documents/{OFFER_ID}/delete", json={"filename": "../../SENTINEL_secret.txt"})
    assert resp.status_code == 400
    body = resp.get_json()
    assert "SENTINEL" not in body["error"]
    assert str(offer_runtime["root"]) not in body["error"]


# ---------------------------------------------------------------------------
# Helper-level unit coverage (no app / no DATA_DIR needed)
# ---------------------------------------------------------------------------

class TestFileSafetyHelper:
    @pytest.mark.parametrize("name", ["umowa.pdf", "Umowa najmu 2026.pdf", "Zażółć gęślą jaźń.docx", "raport (final).xlsx"])
    def test_document_validation_preserves_unicode_and_spaces(self, name):
        assert file_safety.validate_document_filename(name) == name

    @pytest.mark.parametrize("name", TRAVERSAL_NAMES + ["C:\\x", "a:b", "\x00.pdf", " "])
    def test_document_validation_rejects_unsafe(self, name):
        with pytest.raises(file_safety.UnsafeFilename):
            file_safety.validate_document_filename(name)

    def test_image_grammar_matches_media_layer(self):
        # media.py imports the same regex object; prove they are identical.
        from blueprints.media import media as media_module
        assert media_module._OFFER_IMAGE_RE is file_safety.OFFER_IMAGE_RE

    @pytest.mark.parametrize("name", ["image_7_url_0.jpg", "image_7_url_12.WEBP"])
    def test_image_validation_accepts_matching_id(self, name):
        assert file_safety.validate_offer_image_filename(7, name) == name

    @pytest.mark.parametrize("name", ["image_8_url_0.jpg", "image_7_url_0.gif", "../x", "thumbnail.jpg"])
    def test_image_validation_rejects_mismatch(self, name):
        with pytest.raises(file_safety.UnsafeFilename):
            file_safety.validate_offer_image_filename(7, name)
