"""Unit tests for SubjectScheme."""
from __future__ import annotations

from ana.subjects import SubjectScheme


def test_default_scheme_builds_expected_subjects() -> None:
    s = SubjectScheme()
    assert s.query("alice", "status") == "cc.fleet.alice.query.status"
    assert s.reply("alice", "status") == "cc.fleet.alice.reply.status"
    assert s.ack("alice", "status") == "cc.fleet.alice.ack.status"
    assert s.discovery("alice") == "cc.fleet.alice.discovery"
    assert s.policy("alice") == "cc.fleet.alice.policy"
    assert s.pulse("alice") == "cc.fleet.alice.pulse"
    assert s.alert("alice", "context-saved") == "cc.fleet.alice.alert.context-saved"
    assert s.broadcast("alert", "ana-v040-release") == "cc.fleet.broadcast.alert.ana-v040-release"
    assert s.all_broadcasts() == "cc.fleet.broadcast.>"


def test_custom_prefix() -> None:
    s = SubjectScheme(prefix="myfleet.v1")
    assert s.query("alice", "status") == "myfleet.v1.alice.query.status"
    assert s.all_under_prefix() == "myfleet.v1.>"
    assert s.all_for_agent("alice") == "myfleet.v1.alice.>"


def test_parse_well_formed() -> None:
    s = SubjectScheme()
    p = s.parse("cc.fleet.alice.query.status")
    assert p.prefix == "cc.fleet"
    assert p.agent == "alice"
    assert p.verb == "query"
    assert p.topic == "status"
    assert p.is_well_formed


def test_parse_multi_part_topic() -> None:
    s = SubjectScheme()
    p = s.parse("cc.fleet.alice.query.deep.nested.topic")
    assert p.agent == "alice"
    assert p.verb == "query"
    assert p.topic == "deep.nested.topic"


def test_parse_no_topic() -> None:
    s = SubjectScheme()
    p = s.parse("cc.fleet.alice.discovery")
    assert p.agent == "alice"
    assert p.verb == "discovery"
    assert p.topic is None
    assert p.is_well_formed


def test_parse_wrong_prefix_returns_empty() -> None:
    s = SubjectScheme()
    p = s.parse("other.prefix.alice.query.status")
    assert p.prefix is None
    assert p.agent is None
    assert not p.is_well_formed


def test_verb_without_topic() -> None:
    s = SubjectScheme()
    assert s.verb("alice", "discovery") == "cc.fleet.alice.discovery"
    assert s.verb("alice", "query", "status") == "cc.fleet.alice.query.status"


def test_two_prefix_isolation() -> None:
    """Different prefixes don't mistakenly parse each other's subjects."""
    s1 = SubjectScheme(prefix="cc.fleet")
    s2 = SubjectScheme(prefix="cc.other")
    p = s1.parse("cc.other.alice.query.status")
    assert p.prefix is None
    p2 = s2.parse("cc.other.alice.query.status")
    assert p2.prefix == "cc.other"
