import pytest
import requests

from GramAddict.core.qdrant_memory import QdrantBase


@pytest.mark.live_llm
def test_embedding_context_length_limit():
    """
    TDD Proof: Ensure _get_embedding truncates input sufficiently to avoid
    'input length exceeds the context length' (500) from Ollama.
    """

    class DummyMemory(QdrantBase):
        def __init__(self):
            # Bypass init connection checks for this test
            self._vector_size = 768
            pass

    memory = DummyMemory()

    # Mock config to use standard local embedding endpoint
    class FakeArgs:
        ai_embedding_model = "nomic-embed-text"
        ai_embedding_url = "http://localhost:11434/api/embeddings"

    memory._cached_args = FakeArgs()

    # Generate an extremely long string (e.g. 15,000 chars) that would crash Ollama
    huge_text = "lorem ipsum " * 2000

    # This should NOT raise a requests.exceptions.HTTPError (500)
    try:
        vector = memory._get_embedding(huge_text)
        assert vector is not None, "Vector should not be None for successful API calls"
        assert len(vector) > 0, "Vector should have dimensions"
    except requests.exceptions.HTTPError as e:
        pytest.fail(f"Embedding API crashed with HTTP error (likely context limit): {e}")


@pytest.mark.live_llm
def test_structural_signature_truncation():
    """
    Ensure UIMemoryDB correctly truncates structural signatures to 2000 chars.
    """
    from GramAddict.core.qdrant_memory import UIMemoryDB

    db = UIMemoryDB()

    # Huge XML-like string
    huge_xml = "<node " + ('text="junk" ' * 1000) + "/>"

    sig = db._create_structural_signature(huge_xml)
    assert len(sig) <= 2000, f"Signature length {len(sig)} exceeds 2000"
    assert "text=" not in sig, "Structural signature should have removed 'text' attributes"
