"""QA: "Show Adarsh attendance details?" from an employee came back as a bare
guardrail - intent "blocked", no card - instead of the "Access restricted"
card the design shows for someone else's record.

The ownership guard's refusal now carries the card (an `access_notice` with
title "Access restricted" and reason "other_employee_record") and its own
intent, access_notice.RESTRICTED_INTENT. main.py streams the card, closes with that
intent, and saves both so history renders the same card. Who may see another
employee's attendance is still decided by permission_service - the
/leave/context is_manager / is_hr the manager gate resolved.
"""

import json
from unittest.mock import AsyncMock, patch

import pytest

import main
import services.access_notice as access_notice
import services.ownership_guard as og


@pytest.fixture
def other_label(monkeypatch):
    async def _other(prompt, labels, fallback_label="unknown"):
        return "other", None, True
    monkeypatch.setattr(og, "classify_intent_structured", _other)


class _Writer:
    def __init__(self):
        self.events = []

    def __call__(self, e):
        self.events.append(e)


@pytest.mark.usefixtures("other_label")
async def test_an_employees_refusal_carries_the_access_restricted_card():
    writer = _Writer()
    out = await og.ownership_guard_node(
        {"query": "Show Adarsh attendance details?", "bearer_token": "a.e30.c",
         "is_manager": False, "is_hr_role": False}, writer)

    assert out == {"blocked": True}
    event = writer.events[0]
    assert event["type"] == "guardrail" and event["status"] == "failed"
    assert event["intent"] == access_notice.RESTRICTED_INTENT
    notice = event["access_notice"]
    assert notice["title"] == "Access restricted"
    assert notice["reason"] == access_notice.REASON_OTHER_EMPLOYEE
    assert notice["message"] == event["message"]
    # Never confirms whether "Adarsh" exists or has records.
    assert "Adarsh" not in notice["message"]


@pytest.mark.usefixtures("other_label")
@pytest.mark.parametrize("role", [{"is_manager": True}, {"is_hr_role": True}])
async def test_a_manager_or_hr_is_not_refused(role):
    writer = _Writer()
    out = await og.ownership_guard_node(
        {"query": "Show Adarsh attendance details?", "bearer_token": "a.e30.c", **role}, writer)

    assert out == {"blocked": False}
    assert writer.events == []


async def _stream(graph_events):
    async def _astream(state, stream_mode=None):
        for ev in graph_events:
            yield ev

    saved = []
    with patch.object(main.hr_graph, "astream", _astream), \
            patch.object(main, "_finalize_ai_stream", AsyncMock()), \
            patch.object(main, "save_message", lambda db, c, u, q, payload: saved.append(payload)):
        chunks = [c async for c in main._ai_stream("q", [], "conv", 1, False, {}, None, 0.0, "1.2.3.4")]
    return [json.loads(c.split("data:", 1)[1]) for c in chunks if "data:" in c], saved


async def test_main_streams_the_card_and_closes_with_the_restricted_intent():
    notice = access_notice.build_restricted("other_employee_attendance", "Sorry, not yours.")
    payloads, saved = await _stream([{"type": "guardrail", "stage": "input", "status": "failed",
                                      "message": "Sorry, not yours.",
                                      "intent": access_notice.RESTRICTED_INTENT, "access_notice": notice}])

    assert [p for p in payloads if p.get("type") == "access_notice"][0]["data"] == notice
    done = [p for p in payloads if p.get("type") == "done"][-1]
    assert done["intent"] == access_notice.RESTRICTED_INTENT
    assert done["data"]["access_notice"] == notice
    assert saved[0]["intent"] == access_notice.RESTRICTED_INTENT          # history renders the card too
    assert saved[0]["data"]["access_notice"] == notice


async def test_a_safety_refusal_without_a_card_is_unchanged():
    payloads, saved = await _stream([{"type": "guardrail", "stage": "input", "status": "failed",
                                      "message": "Flagged."}])

    assert not [p for p in payloads if p.get("type") == "access_notice"]
    assert [p for p in payloads if p.get("type") == "done"][-1]["intent"] == "blocked"
    assert saved[0]["intent"] == "blocked"


def test_the_restricted_answer_is_never_cached():
    assert access_notice.RESTRICTED_INTENT in main._STATEFUL_QUERY_INTENTS
