"""Unit tests for per-source /search result shaping."""
from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))

from app.links import build_result  # noqa: E402


def _chunk(envelope_id="paperless:119", dist=0.34, chunk_index=2, text="hit text"):
    return {"envelope_id": envelope_id, "dist": dist, "chunk_index": chunk_index, "text": text}


class TestBuildResultPaperless:
    def test_shape_and_link(self):
        envelope = {"source": "paperless", "entities": []}
        result = build_result(_chunk(envelope_id="paperless:119"), envelope)
        assert result["source"] == "paperless"
        assert result["link"] == "https://paper.kapala.org/documents/119/details"
        assert "subject" not in result
        assert "mail_ui_url" not in result


class TestBuildResultGmail:
    def test_shape_and_headers(self):
        envelope = {
            "source": "gmail",
            "entities": [
                {
                    "type": "headers",
                    "from": {"name": "Promocja Lunchroom", "address": "promocja@lunchroom.pl"},
                    "subject": "-20% w wybranych restauracjach",
                    "date_raw": "Wed, 9 May 2018 10:03:32 +0200",
                }
            ],
        }
        result = build_result(_chunk(envelope_id="<msgid@example.com>"), envelope)
        assert result["source"] == "gmail"
        assert result["subject"] == "-20% w wybranych restauracjach"
        assert result["from"] == "Promocja Lunchroom <promocja@lunchroom.pl>"
        assert result["date"] == "Wed, 9 May 2018 10:03:32 +0200"
        assert result["link"] is None
        assert result["mail_ui_url"] is None

    def test_from_without_name_falls_back_to_address(self):
        envelope = {
            "source": "gmail",
            "entities": [
                {"type": "headers", "from": {"name": None, "address": "a@b.com"}, "subject": "s", "date_raw": "d"}
            ],
        }
        result = build_result(_chunk(), envelope)
        assert result["from"] == "a@b.com"

    def test_missing_headers_entity_yields_none_fields(self):
        envelope = {"source": "gmail", "entities": []}
        result = build_result(_chunk(), envelope)
        assert result["subject"] is None
        assert result["from"] is None
        assert result["date"] is None


class TestBuildResultEdgeCases:
    def test_unknown_source_gets_null_link_no_extra_fields(self):
        result = build_result(_chunk(), {"source": "mystery", "entities": []})
        assert result["source"] == "mystery"
        assert result["link"] is None
        assert "subject" not in result

    def test_missing_envelope_does_not_crash(self):
        # e.g. a chunk whose envelope vanished between embedding and query time.
        result = build_result(_chunk(), None)
        assert result["source"] == "unknown"
        assert result["link"] is None
