import pytest
from aura_core.context.engine import (
    ContextAssembler,
    build_domain_context,
    build_generation_context,
)
from aura_core.types import ContextBlock


class TestContextBlock:
    def test_creation(self):
        cb = ContextBlock(source="domain", content="test.com analysis", priority=10)
        assert cb.source == "domain"
        assert cb.priority == 10

    def test_default_priority(self):
        cb = ContextBlock(source="global", content="rules")
        assert cb.priority == 0


class TestContextAssembler:
    def test_empty(self):
        ca = ContextAssembler()
        assert ca.render() == ""

    def test_add_block(self):
        ca = ContextAssembler()
        ca.add(ContextBlock(source="test", content="hello", priority=0))
        output = ca.render()
        assert "hello" in output

    def test_priority_ordering(self):
        ca = ContextAssembler()
        ca.add(ContextBlock(source="low", content="LOW", priority=1))
        ca.add(ContextBlock(source="high", content="HIGH", priority=10))
        output = ca.render()
        high_pos = output.index("HIGH")
        low_pos = output.index("LOW")
        assert high_pos < low_pos

    def test_deduplication(self):
        ca = ContextAssembler()
        ca.add(ContextBlock(source="same", content="DUPE", priority=0))
        ca.add(ContextBlock(source="same", content="DUPE", priority=0))
        output = ca.render()
        assert output.count("DUPE") == 1

    def test_max_tokens_truncation(self):
        ca = ContextAssembler()
        ca.add(ContextBlock(source="big", content="word " * 10000, priority=0))
        output = ca.render(max_chars=500)
        assert len(output) <= 600

    def test_section_headers(self):
        ca = ContextAssembler()
        ca.add(ContextBlock(source="rules", content="Be helpful", priority=5))
        output = ca.render()
        assert "rules" in output.lower() or "---" in output


class TestBuildDomainContext:
    def test_basic(self):
        ctx = build_domain_context("test.com", analysis={"niches": [{"name": "Test"}]})
        assert isinstance(ctx, str)
        assert "test.com" in ctx

    def test_empty_analysis(self):
        ctx = build_domain_context("test.com")
        assert "test.com" in ctx


class TestBuildGenerationContext:
    def test_basic(self):
        ctx = build_generation_context(
            domain="test.com",
            niche="Software Testing",
            brand={"name": "TestBrand", "tagline": "Quality First"},
        )
        assert isinstance(ctx, str)
        assert "test.com" in ctx
        assert "TestBrand" in ctx

    def test_minimal(self):
        ctx = build_generation_context(domain="test.com")
        assert "test.com" in ctx
