"""
Link Injection Engine
Injects internal links into content HTML
"""
import logging
import re
from typing import List, Dict
from igny8_core.business.content.models import Content

logger = logging.getLogger(__name__)


class InjectionEngine:
    """Injects links into content HTML"""
    
    def inject_links(self, content: Content, candidates: List[Dict], max_links: int = 5) -> Dict:
        """
        Inject links into content HTML.
        
        Args:
            content: Content instance
            candidates: List of link candidates from CandidateEngine
            max_links: Maximum number of links to inject
        
        Returns:
            Dict with: {'html_content', 'links', 'links_added'}
        """
        if not content.html_content or not candidates:
            return {
                'html_content': content.html_content,
                'links': [],
                'links_added': 0
            }
        
        html = content.html_content
        links_added = []
        links_used = set()  # Track which candidates we've used
        
        # Sort candidates by relevance score
        sorted_candidates = sorted(candidates, key=lambda x: x.get('relevance_score', 0), reverse=True)
        
        # Inject links (limit to max_links)
        for candidate in sorted_candidates[:max_links]:
            if candidate['content_id'] in links_used:
                continue
            
            anchor_text = candidate.get('anchor_text', 'Learn more')
            url = candidate.get('url', f"/content/{candidate['content_id']}/")
            
            # Find first occurrence of anchor text in HTML (case-insensitive)
            pattern = re.compile(re.escape(anchor_text), re.IGNORECASE)
            match = pattern.search(html)
            
            if match:
                # Replace with link
                link_html = f'<a href="{url}" class="internal-link">{anchor_text}</a>'
                html = html[:match.start()] + link_html + html[match.end():]
                
                links_added.append({
                    'content_id': candidate['content_id'],
                    'anchor_text': anchor_text,
                    'url': url,
                    'position': match.start()
                })
                links_used.add(candidate['content_id'])
        
        return {
            'html_content': html,
            'links': links_added,
            'links_added': len(links_added)
        }


