"""
Tests for the concept extraction service.
"""

from unittest.mock import MagicMock, patch

from django.test import TestCase

from library.services.concepts import ConceptExtractor


class ConceptExtractionParsingTests(TestCase):
    """Tests for concept response parsing."""

    def setUp(self):
        self.mock_model = MagicMock()
        self.mock_model.api.api_type = "openai"
        self.mock_model.api.base_url = "http://localhost:8080/v1"
        self.mock_model.api.api_key = "test"
        self.mock_model.api.timeout_seconds = 30
        self.mock_model.name = "test-chat"
        self.extractor = ConceptExtractor(self.mock_model)

    def test_parse_valid_json_array(self):
        response = '[{"name": "python", "type": "topic"}, {"name": "django", "type": "technique"}]'
        result = self.extractor._parse_concept_response(response)
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0]["name"], "python")
        self.assertEqual(result[1]["type"], "technique")

    def test_parse_json_in_markdown_code_block(self):
        response = '```json\n[{"name": "python", "type": "topic"}]\n```'
        result = self.extractor._parse_concept_response(response)
        self.assertEqual(len(result), 1)

    def test_parse_json_embedded_in_text(self):
        response = 'Here are the concepts: [{"name": "neo4j", "type": "technique"}] found in the text.'
        result = self.extractor._parse_concept_response(response)
        self.assertEqual(len(result), 1)

    def test_parse_invalid_json_returns_empty(self):
        response = "This is not JSON at all."
        result = self.extractor._parse_concept_response(response)
        self.assertEqual(result, [])

    def test_parse_filters_invalid_entries(self):
        response = '[{"name": "valid", "type": "topic"}, {"invalid": "entry"}, "string"]'
        result = self.extractor._parse_concept_response(response)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["name"], "valid")
