import pytest
import json
from unittest.mock import AsyncMock, patch, MagicMock
from aura_core.llm.engine import (
    LLMEngine,
    parse_llm_json,
    build_system_prompt,
)
from aura_core.types import LLMRequest, LLMResponse


class TestParseLlmJson:
    def test_clean_json(self):
        result = parse_llm_json('{"key": "value"}')
        assert result == {"key": "value"}

    def test_json_in_markdown(self):
        text = '```json\n{"key": "value"}\n```'
        result = parse_llm_json(text)
        assert result == {"key": "value"}

    def test_json_with_prefix(self):
        text = 'Here is the result:\n{"key": "value"}'
        result = parse_llm_json(text)
        assert result == {"key": "value"}

    def test_invalid_json_returns_none(self):
        result = parse_llm_json("not json at all")
        assert result is None

    def test_empty_string(self):
        result = parse_llm_json("")
        assert result is None

    def test_nested_json(self):
        data = {"outer": {"inner": [1, 2, 3]}}
        result = parse_llm_json(json.dumps(data))
        assert result == data


class TestBuildSystemPrompt:
    def test_basic(self):
        prompt = build_system_prompt("domain analysis")
        assert "domain analysis" in prompt.lower() or len(prompt) > 10

    def test_with_context(self):
        prompt = build_system_prompt("brand generation", context="fitness niche")
        assert len(prompt) > 20


class TestLLMEngine:
    def test_initialization(self):
        engine = LLMEngine()
        assert engine is not None

    def test_initialization_with_model(self):
        engine = LLMEngine(model="gpt-4o-mini")
        assert engine.model == "gpt-4o-mini"

    def test_request_creation(self):
        req = LLMRequest(prompt="Analyze test.com", max_tokens=4096)
        assert req.prompt == "Analyze test.com"
        assert req.max_tokens == 4096
