import json
import os
import sys

# Ensure src/ is on sys.path for imports
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
SRC = os.path.join(ROOT, "src")
if SRC not in sys.path:
    sys.path.insert(0, SRC)

from fmatch.saas.services.ollama_rerank import _mask_email_user


def test_mask_email_user_masks_local_part():
    assert _mask_email_user("alice@acme.com") == "***@acme.com"
    assert _mask_email_user("ALICE@ACME.COM") == "***@ACME.COM"
    assert _mask_email_user("not-an-email") == "not-an-email"
    assert _mask_email_user("") == ""


def test_candidate_prompt_masking_roundtrip():
    # simulate what _build_prompt() does to candidates
    m = _mask_email_user

    c = {
        "id": "1",
        "name": "Acme Corp",
        "domain": "sales@acme.com",
        "alt": ["info@acme.com", "ACME"],
        "upa": "parent@holding.com",
    }
    # expected masked
    masked = {
        "id": "1",
        "name": "Acme Corp",
        "domain": "***@acme.com",
        "alt": ["***@acme.com", "ACME"],
        "upa": "***@holding.com",
    }
    # inline emulation of masking logic
    cdomain = m(c["domain"]) if "@" in c["domain"] else c["domain"]
    calt = [m(x) if isinstance(x, str) and ("@" in x) else x for x in c["alt"]]
    cupa = m(c["upa"]) if "@" in c["upa"] else c["upa"]
    out = {"id": c["id"], "name": c["name"], "domain": cdomain, "alt": calt, "upa": cupa}

    assert out == masked
    # ensure JSON-serializable like _build_prompt does
    json.dumps(out)

