from __future__ import annotations

import importlib.util
import json
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
MODULE_PATH = REPO_ROOT / "scripts" / "rho_fixture_scrub.py"


def load_module():
    spec = importlib.util.spec_from_file_location("rho_fixture_scrub", MODULE_PATH)
    assert spec is not None
    assert spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


scrub = load_module()


def test_scrub_string_redacts_bearer_and_email():
    text = "Authorization: Bearer abc.def.ghi from madhava@example.com at /Users/madhavajay/dev/rho"
    redacted = scrub.scrub_string(text)
    assert "Bearer [REDACTED]" in redacted
    assert "[REDACTED_EMAIL]" in redacted
    assert "/Users/[REDACTED_USER]" in redacted


def test_scrub_data_redacts_sensitive_keys():
    payload = {
        "headers": {
            "authorization": "Bearer secret-value",
            "x-api-key": "abc123",
        },
        "session_id": "abcd",
        "email": "madhava@example.com",
    }
    redacted = scrub.scrub_data(payload)
    assert redacted["headers"]["authorization"] == "[REDACTED]"
    assert redacted["headers"]["x-api-key"] == "[REDACTED]"
    assert redacted["session_id"] == "[REDACTED]"
    assert redacted["email"] == "[REDACTED_EMAIL]"


def test_scrub_data_redacts_chatgpt_account_id():
    payload = {
        "headers": {
            "authorization": "Bearer secret-value",
            "chatgpt-account-id": "eed62c7e-51f5-4a3b-b71c-986729ade263",
        },
    }
    redacted = scrub.scrub_data(payload)
    assert redacted["headers"]["chatgpt-account-id"] == "[REDACTED]"
    assert "eed62c7e" not in json.dumps(redacted)


def test_scrub_jsonl_text_redacts_nested_headers():
    line = {
        "headers": {
            "authorization": "Bearer secret.jwt.value",
        },
        "url": "https://chatgpt.com/backend-api/codex/responses",
    }
    text = json.dumps(line) + "\n"
    redacted = scrub.scrub_jsonl_text(text)
    assert "secret.jwt.value" not in redacted
    assert "[REDACTED]" in redacted


def test_scrub_file_rewrites_json(tmp_path: Path):
    path = tmp_path / "result.json"
    path.write_text(
        json.dumps(
            {
                "stdout": "hello madhava@example.com",
                "headers": {"authorization": "Bearer secret"},
            }
        ),
        encoding="utf-8",
    )
    changed = scrub.scrub_file(path)
    assert changed is True
    contents = path.read_text(encoding="utf-8")
    assert "madhava@example.com" not in contents
    assert "secret" not in contents
