# #region Test.Models.Edge [C:1] [TYPE Module] [SEMANTICS test,models,agent,api_key,edge]
# @BRIEF Edge-case coverage for model files — agent.py _uuid(), api_key.py __repr__.
# @RELATION BINDS_TO -> [Models.Agent]
# @RELATION BINDS_TO -> [APIKeyModel]

import pytest


class TestAgentModelEdge:
    """Cover _uuid() function in agent.py (line 14)."""

    def test_uuid_generates_string(self):
        from src.models.agent import _uuid

        uid = _uuid()
        assert isinstance(uid, str)
        assert len(uid) > 20  # UUID4 is 36 chars
        assert uid.count("-") == 4  # Standard UUID format

    def test_uuid_unique(self):
        from src.models.agent import _uuid

        uids = {_uuid() for _ in range(100)}
        assert len(uids) == 100  # All unique

    def test_agent_conversation_defaults(self):
        """AgentConversation creates with defaults."""
        from src.models.agent import AgentConversation

        conv = AgentConversation(user_id="user-1")
        assert conv.user_id == "user-1"
        # id defaults to uuid4 string
        assert isinstance(conv.id, str) or conv.id is None

    def test_agent_message_repr(self):
        """AgentMessage creates with defaults."""
        from src.models.agent import AgentMessage

        msg = AgentMessage(
            conversation_id="conv-1",
            role="user",
            text="Hello",
            state="sent",
        )
        assert msg.role == "user"
        assert msg.text == "Hello"
        assert msg.state == "sent"


class TestApiKeyModelEdge:
    """Cover __repr__ in api_key.py (line 33)."""

    def test_repr(self):
        from src.models.api_key import APIKey

        key = APIKey(
            key_hash="a" * 64,
            prefix="ssk_abc1234",
            name="Test Key",
            permissions=["maintenance:start"],
        )
        rep = repr(key)
        assert "ssk_abc1234" in rep
        assert "Test Key" in rep
        assert "APIKey" in rep

    def test_repr_in_db(self, clean_db):
        from src.models.api_key import APIKey

        key = APIKey(
            key_hash="b" * 64,
            prefix="ssk_xyz7890",
            name="DB Key",
            permissions=[],
        )
        clean_db.add(key)
        clean_db.commit()
        clean_db.refresh(key)

        rep = repr(key)
        assert "ssk_xyz7890" in rep
        assert "DB Key" in rep


# ── Shared fixture ───────────────────────────────────────────────


@pytest.fixture
def clean_db():
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.pool import StaticPool

    from src.models.mapping import Base

    engine = create_engine(
        "sqlite:///:memory:",
        poolclass=StaticPool,
        connect_args={"check_same_thread": False},
    )
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    yield session
    session.close()
# #endregion Test.Models.Edge
