"""
Tests for InjectionEngine
"""
from django.test import TestCase
from igny8_core.business.content.models import Content
from igny8_core.business.linking.services.injection_engine import InjectionEngine
from igny8_core.api.tests.test_integration_base import IntegrationTestBase


class InjectionEngineTests(IntegrationTestBase):
    """Tests for InjectionEngine"""
    
    def setUp(self):
        super().setUp()
        self.engine = InjectionEngine()
        
        # Create content with HTML
        self.content = Content.objects.create(
            account=self.account,
            site=self.site,
            sector=self.sector,
            title="Test Content",
            html_content="<p>This is test content with some keywords and text.</p>",
            word_count=100,
            status='draft'
        )
    
    def test_inject_links_adds_links_to_html(self):
        """Test that links are injected into HTML content"""
        candidates = [{
            'content_id': 1,
            'title': 'Target Content',
            'url': '/content/1/',
            'relevance_score': 50,
            'anchor_text': 'keywords'
        }]
        
        result = self.engine.inject_links(self.content, candidates, max_links=5)
        
        # Check that link was added
        self.assertIn('<a href="/content/1/" class="internal-link">keywords</a>', result['html_content'])
        self.assertEqual(result['links_added'], 1)
        self.assertEqual(len(result['links']), 1)
    
    def test_inject_links_respects_max_links(self):
        """Test that max_links limit is respected"""
        candidates = [
            {'content_id': i, 'title': f'Content {i}', 'url': f'/content/{i}/', 
             'relevance_score': 50, 'anchor_text': f'keyword{i}'}
            for i in range(10)
        ]
        
        # Update HTML to include all anchor texts
        self.content.html_content = "<p>" + " ".join([f'keyword{i}' for i in range(10)]) + "</p>"
        self.content.save()
        
        result = self.engine.inject_links(self.content, candidates, max_links=3)
        
        self.assertLessEqual(result['links_added'], 3)
        self.assertLessEqual(len(result['links']), 3)
    
    def test_inject_links_returns_unchanged_when_no_candidates(self):
        """Test that content is unchanged when no candidates"""
        original_html = self.content.html_content
        
        result = self.engine.inject_links(self.content, [], max_links=5)
        
        self.assertEqual(result['html_content'], original_html)
        self.assertEqual(result['links_added'], 0)
        self.assertEqual(len(result['links']), 0)
    
    def test_inject_links_returns_unchanged_when_no_html(self):
        """Test that empty HTML returns unchanged"""
        self.content.html_content = ""
        self.content.save()
        
        candidates = [{
            'content_id': 1,
            'title': 'Target',
            'url': '/content/1/',
            'relevance_score': 50,
            'anchor_text': 'test'
        }]
        
        result = self.engine.inject_links(self.content, candidates, max_links=5)
        
        self.assertEqual(result['html_content'], "")
        self.assertEqual(result['links_added'], 0)
    
    def test_inject_links_case_insensitive_matching(self):
        """Test that anchor text matching is case-insensitive"""
        self.content.html_content = "<p>This is TEST content.</p>"
        self.content.save()
        
        candidates = [{
            'content_id': 1,
            'title': 'Target',
            'url': '/content/1/',
            'relevance_score': 50,
            'anchor_text': 'test'
        }]
        
        result = self.engine.inject_links(self.content, candidates, max_links=5)
        
        # Should find and replace despite case difference
        self.assertIn('internal-link', result['html_content'])
        self.assertEqual(result['links_added'], 1)
    
    def test_inject_links_prevents_duplicate_links(self):
        """Test that same candidate is not linked twice"""
        candidates = [
            {
                'content_id': 1,
                'title': 'Target',
                'url': '/content/1/',
                'relevance_score': 50,
                'anchor_text': 'test'
            },
            {
                'content_id': 1,  # Same content_id
                'title': 'Target',
                'url': '/content/1/',
                'relevance_score': 40,
                'anchor_text': 'test'
            }
        ]
        
        self.content.html_content = "<p>This is test content with test keywords.</p>"
        self.content.save()
        
        result = self.engine.inject_links(self.content, candidates, max_links=5)
        
        # Should only add one link despite two candidates
        self.assertEqual(result['links_added'], 1)
        self.assertEqual(result['html_content'].count('internal-link'), 1)

