"""
Document UI Helper utility for Streamlit UI rendering.
Extracted from document_base.py DocumentUIHelper class.
"""
import os
import hashlib


class DocumentUIHelper:
    """
    Utility class for rendering document-related UI components in Streamlit.
    Provides methods for rendering search results, document analysis, and find results.
    """
    
    @staticmethod
    def _generate_unique_key(base_key, *args):
        """Generate unique key for widgets to avoid duplicates in history"""
        combined = f"{base_key}_{'_'.join(map(str, args))}"
        return hashlib.md5(combined.encode()).hexdigest()[:12]
    
    @staticmethod
    def render_document_search(st_module, results, avatar_url, is_history=False):
        """Render @file search results - matching chat tab UI exactly"""
        asst_msg = st_module.chat_message("assistant", avatar=avatar_url)
        
        asst_msg.markdown(f"### 🔍 Results: {results['query']}")
        
        if results.get('folder_detected'):
            asst_msg.success(f"🔍 Auto-detected folder: **{results['folder_detected']}**")
        
        if results.get('overall_summary'):
            with asst_msg.expander("📝 AI Summary", expanded=True):
                asst_msg.markdown(results['overall_summary'])
        
        chunk_hits = results.get('chunk_hits') or []
        asst_msg.caption(
            f"📊 {len(chunk_hits)} chunk matches"
        )
        asst_msg.markdown("---")

        if chunk_hits:
            asst_msg.markdown("### Chunk matches")
            for idx, hit in enumerate(chunk_hits[:10]):
                chunk_label = hit.get('chunk_id') or f"chunk_{idx}"
                pages = hit.get('page_numbers') or hit.get('page_span') or ''
                title = f"📄 {hit.get('filename', 'Unknown')} • {chunk_label} • {hit.get('relevance', 0):.1f}%"
                if pages:
                    title += f" • p.{pages}"
                with asst_msg.expander(title, expanded=(idx < 2)):
                    asst_msg.write((hit.get('chunk_text') or hit.get('summary') or '')[:500])
                    relevant = hit.get('relevant_images') or []
                    if relevant:
                        cols = asst_msg.columns(min(len(relevant), 5))
                        for i, img in enumerate(relevant):
                            with cols[i % min(len(relevant), 5)]:
                                if os.path.exists(img.get('path', '')):
                                    st_module.image(img['path'], use_container_width=True)
                                    st_module.caption(f"P{img.get('page', '?')}")
            asst_msg.markdown("---")
        
        for folder_name, docs in results.get('folder_groups', {}).items():
            asst_msg.markdown(f"### 📁 {folder_name} ({len(docs)} files)")
            
            for doc_idx, doc in enumerate(docs):
                doc_key = DocumentUIHelper._generate_unique_key(
                    "doc_search", folder_name, doc_idx, doc['file_id']
                )
                
                chunk_id = doc.get('chunk_id') or ''
                chunk_suffix = f" • {chunk_id}" if chunk_id else ""
                with asst_msg.expander(
                    f"📄 {doc['filename']}{chunk_suffix} • {doc['relevance']:.1f}% match",
                    expanded=False,
                ):
                    if doc.get('relative_path'):
                        asst_msg.caption(f"📍 {doc['relative_path']}")
                    
                    asst_msg.markdown("**📋 Preview:**")
                    asst_msg.write(doc['summary'])
                    
                    col1, col2, col3 = asst_msg.columns(3)
                    with col1:
                        st_module.metric("Relevance", f"{doc['relevance']:.1f}%")
                    with col2:
                        st_module.metric("Type", doc.get('file_type', 'Unknown').upper())
                    with col3:
                        st_module.metric("Images", len(doc.get('relevant_images', [])))
                    
                    asst_msg.markdown("---")
                    
                    col_btn2, col_btn4 = asst_msg.columns(2)
                    
                    with col_btn2:
                        images_key = f"images_{doc_key}"
                        if st_module.button("🖼️ Images", key=images_key):
                            toggle_key = f"show_images_{doc['file_id']}"
                            st_module.session_state[toggle_key] = not st_module.session_state.get(toggle_key, False)
                            st_module.rerun()
                    
                    with col_btn4:
                        if os.path.exists(doc['file_path']):
                            with open(doc['file_path'], 'rb') as f:
                                dl_key = f"dl_{doc_key}"
                                st_module.download_button(
                                    "⬇️ Download", f, file_name=doc['filename'], key=dl_key
                                )
                    
                    if st_module.session_state.get(f"show_images_{doc['file_id']}", False):
                        relevant = doc.get('relevant_images') or []
                        if relevant:
                            asst_msg.markdown("**🖼️ Relevant page images:**")
                            if doc.get('page_numbers'):
                                asst_msg.caption(f"Pages: {doc['page_numbers']}")
                            num_images = len(relevant)
                            cols = asst_msg.columns(min(num_images, 10))
                            for i, img in enumerate(relevant):
                                col_idx = i % min(num_images, 10)
                                with cols[col_idx]:
                                    if os.path.exists(img['path']):
                                        st_module.image(img['path'], use_container_width=True)
                                        st_module.caption(f"P{img['page']}")
    
    @staticmethod
    def render_document_analysis(st_module, analysis, avatar_url, is_history=False):
        """Render @analyze results - matching chat tab UI exactly"""
        asst_msg = st_module.chat_message("assistant", avatar=avatar_url)
        
        asst_msg.markdown(f"### 📊 Analysis: {analysis['filename']}")
        asst_msg.caption(f"📁 Folder: {analysis.get('folder_path', 'Root')}")
        
        if analysis.get('relative_path'):
            asst_msg.caption(f"📍 Path: {analysis['relative_path']}")
        
        if analysis.get('folder_detected'):
            asst_msg.success(f"🔍 Auto-detected folder: **{analysis['folder_detected']}**")
        
        with asst_msg.expander("🤖 Detailed Analysis", expanded=True):
            asst_msg.write(analysis.get('analysis', 'No analysis available'))
        
        col1, col2 = asst_msg.columns(2)
        with col1:
            st_module.metric("File Type", analysis.get('file_type', 'Unknown').upper())
        with col2:
            st_module.metric("Total Images", len(analysis.get('all_images', [])))
        
        if analysis.get('all_images'):
            asst_msg.markdown("### 🖼️ Document Images")
            
            num_images = len(analysis['all_images'])
            cols = asst_msg.columns(num_images)
            
            for i, img in enumerate(analysis['all_images']):
                with cols[i]:
                    if isinstance(img, dict):
                        img_path = img.get('path', '')
                        img_type = img.get('type', 'Image')
                        page_num = img.get('page', 1)
                        if img_path and os.path.exists(img_path):
                            st_module.image(img_path, use_container_width=True)
                            st_module.caption(f"P{page_num} - {img_type}")
    
    @staticmethod
    def render_document_find(st_module, results, avatar_url, is_history=False):
        """Render @find results - matching chat tab UI exactly"""
        asst_msg = st_module.chat_message("assistant", avatar=avatar_url)
        
        if not results.get('results'):
            asst_msg.warning(f"❌ No matches found for: **{results['query']}**")
            if results.get('folder_detected'):
                asst_msg.info(f"Searched in folder: {results['folder_detected']}")
            return
        
        doc = results['results'][0]
        
        asst_msg.success(f"✅ Best Match: **{doc['filename']}**")
        asst_msg.caption(f"📁 {doc.get('folder_path', 'Root')}")
        
        if doc.get('relative_path'):
            asst_msg.caption(f"📍 {doc['relative_path']}")
        
        if results.get('folder_detected'):
            asst_msg.info(f"🔍 Auto-detected folder: {results['folder_detected']}")
        
        col1, col2, col3, col4 = asst_msg.columns(4)
        with col1:
            st_module.metric("Relevance", f"{doc['relevance_score']}%")
        with col2:
            st_module.metric("Exact Matches", doc['match_count'])
        with col3:
            st_module.metric("Pages", len(doc.get('matching_pages', [])))
        with col4:
            if results.get('total_files_searched'):
                st_module.metric("Files Searched", results['total_files_searched'])
        
        if doc.get('matching_pages'):
            pages_str = ', '.join(map(str, doc['matching_pages'][:10]))
            if len(doc['matching_pages']) > 10:
                pages_str += f" ... +{len(doc['matching_pages']) - 10} more"
            asst_msg.info(f"📄 Found on pages: {pages_str}")
        
        asst_msg.markdown("---")
        
        if doc.get('ai_summary'):
            with asst_msg.expander("🤖 AI Summary", expanded=True):
                asst_msg.markdown(doc['ai_summary'])
        
        asst_msg.markdown("### 🔍 Matching Content")
        for i, match in enumerate(doc.get('matches', [])[:5]):
            match_key = DocumentUIHelper._generate_unique_key(
                "match", doc.get('filename', 'doc'), i
            )
            with asst_msg.expander(f"Match {i+1}", expanded=(i < 2)):
                st_module.code(match, language="text")
        
        relevant = doc.get('relevant_images') or []
        if relevant:
            asst_msg.markdown("### 🖼️ Relevant page images")
            if doc.get('matching_pages'):
                asst_msg.caption(f"Pages: {', '.join(map(str, doc['matching_pages']))}")
            num_images = len(relevant)
            cols = asst_msg.columns(num_images)
            for i, img in enumerate(relevant):
                with cols[i]:
                    if os.path.exists(img.get('path', '')):
                        st_module.image(img['path'], use_container_width=True)
                        st_module.caption(f"P{img.get('page', '?')} - {img.get('type', 'page_snapshot')}")
        
        asst_msg.markdown("---")
        if os.path.exists(doc['file_path']):
            with open(doc['file_path'], 'rb') as f:
                dl_key = DocumentUIHelper._generate_unique_key(
                    "dl_find", doc.get('filename', 'doc')
                )
                asst_msg.download_button(
                    "⬇️ Download Document", 
                    f, 
                    file_name=doc['filename'], 
                    use_container_width=True, 
                    key=dl_key
                )
