"""
Streamlit page for generating knowledge cards from contextual elements.
"""

import streamlit as st
import sys
from pathlib import Path
import json

# Add the module path to PYTHONPATH
sys.path.append(str(Path(__file__).parent.parent))

from utils.llm.utils_llm import (
    generate_knowledge_card,
    generate_visual_summary, 
    generate_comparative_analysis,
    ask_llm
)

from openai import OpenAI


def setup_openai_client(api_base: str, api_key: str) -> OpenAI:
    """Configure the OpenAI client."""
    return OpenAI(base_url=api_base, api_key=api_key)


def main():
    st.set_page_config(
        page_title="Knowledge Card Generation",
        page_icon="📋",
        layout="wide"
    )
    
    st.title("📋 Knowledge Card Generation")
    st.markdown("---")
    
    # LLM configuration in the sidebar
    with st.sidebar:
        st.header("⚙️ LLM Configuration")
        
        api_base = st.text_input(
            "API Base URL",
            value="http://localhost:11434/v1",
            help="URL for local Ollama or any OpenAI-compatible API"
        )
        
        api_key = st.text_input(
            "API Key",
            value="ollama",
            type="password",
            help="API key (for local Ollama, use 'ollama')"
        )
        
        model_name = st.text_input(
            "Model name",
            value="phi3.5:latest",
            help="Name of the LLM model to use"
        )
        
        # Connection test
        if st.button("🔌 Test connection"):
            try:
                client = setup_openai_client(api_base, api_key)
                response = client.chat.completions.create(
                    model=model_name,
                    messages=[{"role": "user", "content": "Test. Reply 'OK'."}],
                    max_tokens=5,
                    timeout=10
                )
                if response.choices[0].message.content:
                    st.success("✅ Connection successful!")
                    st.session_state.llm_connected = True
            except Exception as e:
                st.error(f"❌ Connection error: {e}")
                st.session_state.llm_connected = False
        
        st.markdown("---")
        
        st.header("🎛️ Options")
        
        # Output format
        output_format = st.selectbox(
            "Output format",
            ["Knowledge card", "Visual summary", "Comparative analysis"]
        )
        
        if output_format == "Visual summary":
            visual_type = st.selectbox(
                "Visualization type",
                ["mindmap", "schema", "timeline", "process"]
            )
        
        # Advanced options
        with st.expander("Advanced options"):
            temperature = st.slider("Creativity (temperature)", 0.0, 1.0, 0.3)
            max_tokens = st.slider("Max length (tokens)", 100, 2000, 800)
    
    # Main interface
    col1, col2 = st.columns([1, 1])
    
    with col1:
        st.header("📝 Content input")
        
        # Input methods
        input_method = st.radio(
            "How would you like to provide the content?",
            ["Manual input", "File upload", "Predefined examples"]
        )
        
        context_text = ""
        title = ""
        
        if input_method == "Manual input":
            title = st.text_input("🏷️ Question (optional)", placeholder="e.g., Artificial Intelligence")
            context_text = st.text_area(
                "📋 Content to process",
                height=300,
                placeholder="Enter the text from which you want to generate a knowledge card..."
            )
        
        elif input_method == "File upload":
            uploaded_file = st.file_uploader(
                "📁 Upload a text file",
                type=['txt', 'md', 'json']
            )
            
            if uploaded_file is not None:
                try:
                    if uploaded_file.type == "application/json":
                        data = json.load(uploaded_file)
                        context_text = str(data)
                    else:
                        context_text = str(uploaded_file.read(), "utf-8")
                    
                    title = st.text_input("🏷️ Question", value=uploaded_file.name.split('.')[0])
                    
                    st.success(f"✅ File loaded: {len(context_text)} characters")
                    
                    with st.expander("Content preview"):
                        st.text(context_text[:500] + "..." if len(context_text) > 500 else context_text)
                        
                except Exception as e:
                    st.error(f"❌ Read error: {e}")
        
        else:  # Predefined examples
            examples = {
                "Artificial Intelligence": """
Artificial Intelligence (AI) is a revolutionary technology that enables machines to simulate human intelligence.
It includes several fields such as machine learning, natural language processing, and computer vision. 
AI can be divided into narrow AI (specialized in one task) and general AI (general intelligence).

Applications of AI include virtual assistants, speech recognition, recommendation systems, 
autonomous driving, and medical diagnosis. AI uses complex algorithms and neural networks 
to analyze data and make decisions.

AI challenges include ethics, decision transparency, personal data protection, 
and the impact on employment. It is crucial to develop responsible AI that benefits society.
                """,
                
                "Sustainable Development": """
Sustainable development is a development approach that meets present needs without compromising 
the ability of future generations to meet theirs. It is based on three interconnected pillars: 
economic, social, and environmental.

The goals of sustainable development include fighting poverty, protecting the environment, 
social equality, and responsible economic growth. The 17 United Nations Sustainable Development Goals (SDGs) 
provide a global framework to achieve these objectives by 2030.

Key issues include climate change, biodiversity, access to drinking water, renewable energy, 
and the circular economy. Every stakeholder (governments, businesses, citizens) has a role to play.
                """,
                
                "Cybersecurity": """
Cybersecurity is about protecting computer systems, networks, and data against 
digital attacks. It encompasses information security, network security, 
and application security.

Major threats include viruses, malware, phishing, ransomware, and distributed denial-of-service (DDoS) attacks. 
Cybercriminals often target personal data, financial information, and trade secrets.

Protective measures include firewalls, antivirus software, two-factor authentication, data encryption, 
user training, and backup plans. Cybersecurity requires a multilayer approach and constant vigilance.
                """
            }
            
            selected_example = st.selectbox("Choose an example", list(examples.keys()))
            context_text = examples[selected_example]
            title = selected_example
            
            with st.expander("Example preview"):
                st.write(context_text)
        
        # Validation
        if context_text:
            st.success(f"✅ Content ready: {len(context_text)} characters")
        else:
            st.warning("⚠️ Please provide content to process")
    
    with col2:
        st.header("🎯 Generation")
        
        if context_text:
            # Content preview
            with st.expander("📋 Content preview"):
                st.write(f"**Title:** {title if title else 'Untitled'}")
                st.write(f"**Length:** {len(context_text)} characters")
                st.text_area("Content:", value=context_text[:300] + "...", height=100, disabled=True)
            
            # Generation
            if output_format == "Knowledge card":
                if st.button("🚀 Generate knowledge card", type="primary"):
                    with st.spinner("Generating..."):
                        if st.session_state.get('llm_connected', False):
                            try:
                                client = setup_openai_client(api_base, api_key)
                                
                                # Model configuration with parameters
                                def custom_ask_llm(prompt, client):
                                    response = client.chat_completions.create(  # NOTE: unchanged logic expected; adjust if your client uses chat.completions
                                        model=model_name,
                                        messages=[{"role": "user", "content": prompt}],
                                        temperature=temperature,
                                        max_tokens=max_tokens
                                    )
                                    return response.choices[0].message.content
                                
                                # Generation with LLM
                                result = generate_knowledge_card(
                                    context=context_text,
                                    title=title,
                                    client=client
                                )
                                
                                # Temporarily replace ask_llm
                                import utils.llm.utils_llm as llm_module
                                original_ask_llm = llm_module.ask_llm
                                llm_module.ask_llm = custom_ask_llm
                                
                                try:
                                    result = generate_knowledge_card(context_text, title, client)
                                finally:
                                    llm_module.ask_llm = original_ask_llm
                                
                                st.session_state.generated_content = result
                                st.session_state.generated_type = "Knowledge card"
                                
                                st.success("🎉 Card generated successfully!")
                                
                            except Exception as e:
                                st.error(f"❌ Generation error: {e}")
                        else:
                            # Prompt generation only
                            prompt = generate_knowledge_card(
                                context=context_text,
                                title=title,
                                client=None
                            )
                            st.session_state.generated_content = prompt
                            st.session_state.generated_type = "Prompt for knowledge card"
                            st.info("📝 Prompt generated (no LLM connected)")
            
            elif output_format == "Visual summary":
                if st.button("🎨 Generate visual summary", type="primary"):
                    with st.spinner("Generating..."):
                        if st.session_state.get('llm_connected', False):
                            try:
                                client = setup_openai_client(api_base, api_key)
                                
                                def custom_ask_llm(prompt, client):
                                    response = client.chat_completions.create(  # NOTE: unchanged logic expected; adjust if your client uses chat.completions
                                        model=model_name,
                                        messages=[{"role": "user", "content": prompt}],
                                        temperature=temperature,
                                        max_tokens=max_tokens
                                    )
                                    return response.choices[0].message.content
                                
                                import utils.llm.utils_llm as llm_module
                                original_ask_llm = llm_module.ask_llm
                                llm_module.ask_llm = custom_ask_llm
                                
                                try:
                                    result = generate_visual_summary(context_text, visual_type, client)
                                finally:
                                    llm_module.ask_llm = original_ask_llm
                                
                                st.session_state.generated_content = result
                                st.session_state.generated_type = f"Visual summary ({visual_type})"
                                
                                st.success("🎉 Visual summary generated!")
                                
                            except Exception as e:
                                st.error(f"❌ Generation error: {e}")
                        else:
                            prompt = generate_visual_summary(context_text, visual_type, None)
                            st.session_state.generated_content = prompt
                            st.session_state.generated_type = f"Prompt for visual summary ({visual_type})"
                            st.info("📝 Prompt generated (no LLM connected)")
            
            elif output_format == "Comparative analysis":
                st.write("For comparative analysis, you need to provide two contents to compare.")
                
                col_a, col_b = st.columns(2)
                
                with col_a:
                    st.subheader("🔷 Item A")
                    question_a = st.text_input("Question A", value="Item A")
                    context_a = st.text_area("Content A", value=context_text[:len(context_text)//2], height=150)
                
                with col_b:
                    st.subheader("🔶 Item B")
                    question_b = st.text_input("Question B", value="Item B")
                    context_b = st.text_area("Content B", value=context_text[len(context_text)//2:], height=150)
                
                if st.button("⚖️ Generate comparative analysis", type="primary"):
                    with st.spinner("Generating..."):
                        if st.session_state.get('llm_connected', False):
                            try:
                                client = setup_openai_client(api_base, api_key)
                                
                                def custom_ask_llm(prompt, client):
                                    response = client.chat_completions.create(  # NOTE: unchanged logic expected; adjust if your client uses chat.completions
                                        model=model_name,
                                        messages=[{"role": "user", "content": prompt}],
                                        temperature=temperature,
                                        max_tokens=max_tokens
                                    )
                                    return response.choices[0].message.content
                                
                                import utils.llm.utils_llm as llm_module
                                original_ask_llm = llm_module.ask_llm
                                llm_module.ask_llm = custom_ask_llm
                                
                                try:
                                    result = generate_comparative_analysis(context_a, context_b, question_a, question_b, client)
                                finally:
                                    llm_module.ask_llm = original_ask_llm
                                
                                st.session_state.generated_content = result
                                st.session_state.generated_type = "Comparative analysis"
                                
                                st.success("🎉 Comparative analysis generated!")
                                
                            except Exception as e:
                                st.error(f"❌ Generation error: {e}")
                        else:
                            prompt = generate_comparative_analysis(context_a, context_b, question_a, question_b, None)
                            st.session_state.generated_content = prompt
                            st.session_state.generated_type = "Prompt for comparative analysis"
                            st.info("📝 Prompt generated (no LLM connected)")
    
    # Display results
    if 'generated_content' in st.session_state:
        st.markdown("---")
        st.header("📄 Generated result")
        
        st.subheader(f"🎯 {st.session_state.generated_type}")
        
        # Display options
        col1, col2, col3 = st.columns([1, 1, 1])
        
        with col1:
            if st.button("📋 Copy"):
                # Note: Copy would require JavaScript; here we simply display the content
                st.info("Content displayed below for manual copy")
        
        with col2:
            # Download
            st.download_button(
                label="💾 Download",
                data=st.session_state.generated_content,
                file_name=f"{title or 'card'}_{st.session_state.generated_type.lower().replace(' ', '_')}.md",
                mime="text/markdown"
            )
        
        with col3:
            if st.button("🗑️ Clear"):
                del st.session_state.generated_content
                del st.session_state.generated_type
                st.rerun()
        
        # Display content
        st.markdown("### Generated content:")
        
        # Styled display depending on type
        if "Prompt" in st.session_state.generated_type:
            st.code(st.session_state.generated_content, language="markdown")
        else:
            st.markdown(st.session_state.generated_content)
        
        # Statistics
        content_stats = {
            "Length": f"{len(st.session_state.generated_content)} characters",
            "Words": f"{len(st.session_state.generated_content.split())} words",
            "Lines": f"{len(st.session_state.generated_content.split(chr(10)))} lines"
        }
        
        st.sidebar.markdown("### 📊 Result statistics")
        for key, value in content_stats.items():
            st.sidebar.metric(key, value)
    
    # Footer with information
    st.markdown("---")
    st.markdown(
        """
        💡 **Usage tips:**
        - Provide rich and structured content for better results
        - Try different formats depending on your needs
        - Adjust creativity (temperature) depending on the desired content type
        - Prompts can be used with any OpenAI-compatible LLM
        """
    )


if __name__ == "__main__":
    main()
