"""ACL gating + field handling for services/systems.py (unit, mocked session)."""
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
from tests.helpers import make_mock_session


@pytest.mark.asyncio
async def test_create_system_denied_without_project_write():
    with patch("scribe.services.systems.access") as acc:
        acc.can_write_project = AsyncMock(return_value=False)
        from scribe.services.systems import create_system
        result = await create_system(user_id=1, project_id=5, name="Reader")
    assert result is None


@pytest.mark.asyncio
async def test_create_system_sets_fields_when_authorized():
    mock_session = make_mock_session()
    captured = {}

    def _capture_add(obj):
        captured["name"] = getattr(obj, "name", "MISSING")
        captured["project_id"] = getattr(obj, "project_id", "MISSING")

    mock_session.add = MagicMock(side_effect=_capture_add)
    with patch("scribe.services.systems.async_session") as mock_cls, \
         patch("scribe.services.systems.access") as acc:
        acc.can_write_project = AsyncMock(return_value=True)
        mock_cls.return_value = mock_session
        from scribe.services.systems import create_system
        await create_system(user_id=1, project_id=5, name="  Reader  ")
    assert captured["name"] == "Reader"  # stripped
    assert captured["project_id"] == 5


@pytest.mark.asyncio
async def test_set_record_systems_denied_without_note_write():
    with patch("scribe.services.systems.access") as acc:
        acc.can_write_note = AsyncMock(return_value=False)
        from scribe.services.systems import set_record_systems
        result = await set_record_systems(user_id=1, note_id=9, system_ids=[1, 2])
    assert result is None


@pytest.mark.asyncio
async def test_list_systems_denied_returns_empty():
    with patch("scribe.services.systems.access") as acc:
        acc.can_read_project = AsyncMock(return_value=False)
        from scribe.services.systems import list_systems
        result = await list_systems(user_id=1, project_id=5)
    assert result == []


@pytest.mark.asyncio
async def test_count_open_issues_denied_returns_zero():
    with patch("scribe.services.systems.access") as acc:
        acc.can_read_project = AsyncMock(return_value=False)
        from scribe.services.systems import count_open_issues
        result = await count_open_issues(user_id=1, project_id=5)
    assert result == 0


# ── assess_system_name — the one gate both doors call (milestone 307) ──

@pytest.mark.asyncio
async def test_assess_matches_an_existing_system_on_case_and_spacing():
    """The local gate compares the operator's own spelling: case and runs of
    whitespace are not a different System. Anything stronger belongs to the
    CANONICAL slug, which is a different question (is this the same AREA as
    another project's System) with a different answer."""
    existing = MagicMock()
    existing.id, existing.name = 7, "Scrape Pipeline"
    with patch("scribe.services.systems.list_systems", AsyncMock(return_value=[existing])):
        from scribe.services.systems import assess_system_name
        out = await assess_system_name(1, 5, "  scrape   pipeline ")
    assert out["duplicate"] == {"id": 7, "name": "Scrape Pipeline"}
    # A duplicate short-circuits: there is nothing to file when nothing is created.
    assert out["canonical"] is None


@pytest.mark.asyncio
async def test_assess_prefers_an_exact_area_over_a_merely_similar_one():
    from scribe.services.systems import assess_system_name
    exact = MagicMock()
    exact.id, exact.name = 3, "CI & Release"
    with patch("scribe.services.systems.list_systems", AsyncMock(return_value=[])), \
         patch("scribe.services.systems.canonical_systems_svc") as canon:
        canon.find_by_name = AsyncMock(return_value=exact)
        canon.best_overlap = AsyncMock()
        out = await assess_system_name(1, 5, "CI and Release")
    assert out["canonical"] == {"id": 3, "name": "CI & Release", "basis": "exact"}
    # An exact hit is the answer — no need to go looking for a lesser one.
    canon.best_overlap.assert_not_awaited()


@pytest.mark.asyncio
async def test_assess_falls_back_to_overlap_and_never_invents_a_match():
    from scribe.services.systems import assess_system_name
    near = {"id": 3, "name": "CI & Release", "basis": "overlap", "score": 0.33}
    with patch("scribe.services.systems.list_systems", AsyncMock(return_value=[])), \
         patch("scribe.services.systems.canonical_systems_svc") as canon:
        canon.find_by_name = AsyncMock(return_value=None)
        canon.best_overlap = AsyncMock(return_value=near)
        assert (await assess_system_name(1, 5, "CI & runners"))["canonical"] == near
        canon.best_overlap = AsyncMock(return_value=None)
        # Nothing resembles it: a project-specific area, and silence is the
        # right answer — unmapped is a valid resting state.
        assert (await assess_system_name(1, 5, "Soundboard"))["canonical"] is None


@pytest.mark.asyncio
async def test_assess_fails_open_so_a_naming_aid_cannot_block_a_create():
    """Both arms degrade to "no opinion" rather than raising. A create must
    never fail because the catalog was unreachable."""
    from scribe.services.systems import assess_system_name
    with patch("scribe.services.systems.list_systems", AsyncMock(side_effect=RuntimeError("db down"))):
        assert await assess_system_name(1, 5, "Reader") == {"duplicate": None, "canonical": None}
    with patch("scribe.services.systems.list_systems", AsyncMock(return_value=[])), \
         patch("scribe.services.systems.canonical_systems_svc") as canon:
        canon.find_by_name = AsyncMock(side_effect=RuntimeError("db down"))
        assert (await assess_system_name(1, 5, "Reader"))["canonical"] is None


@pytest.mark.asyncio
async def test_assess_says_nothing_about_a_nameless_system():
    from scribe.services.systems import assess_system_name
    assert await assess_system_name(1, 5, "   ") == {"duplicate": None, "canonical": None}
