import streamlit as st
import asyncio
from crewai import Agent, Task, Crew
from langchain_groq import ChatGroq
import time
import os
from dotenv import load_dotenv
import math

# Load environment variables
load_dotenv()

# Get API key from environment variable
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

if not GROQ_API_KEY:
    st.error("GROQ API key not found. Please set the GROQ_API_KEY environment variable.")
    st.stop()

# Page configuration
st.set_page_config(page_title="NeuraNexus: AI-Powered ML Assistant", page_icon="🧠", layout="wide")

# Custom CSS for an advanced, animated, and mobile-responsive UI
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700&family=Roboto:wght@300;400;500;700&display=swap');

    :root {
        --primary: #4A90E2;
        --secondary: #50E3C2;
        --tertiary: #FF6B6B;
        --bg-dark: #0F1C2E;
        --text-light: #FFFFFF;
        --text-dark: #333333;
        --accent: #E94E77;
    }

    body {
        background-color: var(--bg-dark);
        color: var(--text-light);
        font-family: 'Roboto', sans-serif;
        line-height: 1.6;
        background-image: 
            radial-gradient(circle at 10% 20%, rgba(74, 144, 226, 0.2) 0%, rgba(74, 144, 226, 0) 40%),
            radial-gradient(circle at 90% 80%, rgba(80, 227, 194, 0.2) 0%, rgba(80, 227, 194, 0) 40%),
            linear-gradient(to bottom, var(--bg-dark), #1A2B3C);
        background-attachment: fixed;
    }

    .stApp {
        background: rgba(15, 28, 46, 0.85);
        border-radius: 15px;
        padding: 2rem;
        margin-top: 30px;
        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
        backdrop-filter: blur(4px);
        -webkit-backdrop-filter: blur(4px);
        border: 1px solid rgba(255, 255, 255, 0.18);
    }

    h1 {
        font-family: 'Orbitron', sans-serif;
        color: #FF6B6B;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 2px;
        text-align: center;
        font-size: 2.5em;
        margin-bottom: 30px;
        text-shadow: 0 0 10px rgba(255, 107, 107, 0.7);
    }

    h3 {
        font-family: 'Orbitron', sans-serif;
        color: var(--secondary);
        font-weight: 500;
        text-align: center;
        margin-bottom: 20px;
        font-size: 1.2em;
    }

    .stTextInput > div > div > input,
    .stTextArea > div > div > textarea {
        background-color: rgba(255, 255, 255, 0.05);
        color: var(--text-light);
        border: 1px solid var(--primary);
        border-radius: 10px;
        padding: 15px;
        transition: all 0.3s ease;
    }

    .stTextInput > div > div > input:focus,
    .stTextArea > div > div > textarea:focus {
        box-shadow: 0 0 15px var(--primary);
        border-color: var(--secondary);
    }

    .stButton > button {
        background: linear-gradient(45deg, var(--primary), var(--accent));
        color: var(--text-light);
        font-weight: 600;
        border: none;
        border-radius: 30px;
        padding: 0.75rem 2rem;
        text-transform: uppercase;
        letter-spacing: 1px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
        position: relative;
        overflow: hidden;
        display: block;
        margin: 30px auto;
        width: 200px;
    }

    .stButton > button:hover {
        background: linear-gradient(45deg, var(--accent), var(--primary));
        box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
        transform: translateY(-2px);
    }

    .stButton > button::after {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(to bottom right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.13) 77%, rgba(255, 255, 255, 0.5) 92%, rgba(255, 255, 255, 0.0) 100%);
        transform: rotate(-45deg);
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .stButton > button:hover::after {
        opacity: 1;
        animation: shine 1.5s ease-out infinite;
    }

    @keyframes shine {
        to {
            left: 120%;
            top: 100%;
        }
    }

    .result-container {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(74, 144, 226, 0.2);
        border-radius: 15px;
        padding: 20px;
        margin-top: 30px;
        color: var(--text-light);
        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        transition: all 0.3s ease;
    }

    .result-container:hover {
        box-shadow: 0 12px 40px 0 rgba(31, 38, 135, 0.3);
        transform: translateY(-5px);
    }

    /* Neural network animation */
    .neural-network {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        overflow: hidden;
        pointer-events: none;
    }

    .neuron {
        position: absolute;
        background-color: var(--accent);
        border-radius: 50%;
        opacity: 0.5;
        animation: pulse 4s infinite alternate;
    }

    @keyframes pulse {
        0% { transform: scale(1); opacity: 0.5; }
        100% { transform: scale(1.5); opacity: 0.8; }
    }

    .synapse {
        position: absolute;
        background-color: var(--secondary);
        height: 1px;
        animation: synapseFlash 3s infinite linear;
    }

    @keyframes synapseFlash {
        0% { opacity: 0; }
        50% { opacity: 1; }
        100% { opacity: 0; }
    }

    .glow {
        text-shadow: 0 0 10px var(--primary), 0 0 20px var(--primary), 0 0 30px var(--primary);
        animation: textPulse 2s infinite alternate;
    }

    @keyframes textPulse {
        0% { text-shadow: 0 0 10px var(--primary), 0 0 20px var(--primary), 0 0 30px var(--primary); }
        100% { text-shadow: 0 0 15px var(--primary), 0 0 25px var(--primary), 0 0 35px var(--primary); }
    }

    /* By Theaimart text */
    .by-theaimart {
        text-align: center;
        font-size: 33px;
        color: var(--secondary);
        margin-top: 20px;
        opacity: 0.8;
        transition: opacity 0.3s ease;
        font-weight: bold;
    }

    .by-theaimart:hover {
        opacity: 1;
    }

    /* Mobile responsiveness */
    @media (max-width: 768px) {
        h1 {
            font-size: 2em;
        }

        h3 {
            font-size: 1em;
        }

        .stButton > button {
            width: 100%;
            max-width: 200px;
        }

        .result-container {
            padding: 15px;
        }
    }
</style>

<div class="neural-network" id="neuralNetwork"></div>

<script>
    function createNeuralNetwork() {
        const container = document.getElementById('neuralNetwork');
        const numNeurons = 20;
        const numSynapses = 30;

        for (let i = 0; i < numNeurons; i++) {
            const neuron = document.createElement('div');
            neuron.classList.add('neuron');
            neuron.style.left = `${Math.random() * 100}%`;
            neuron.style.top = `${Math.random() * 100}%`;
            neuron.style.width = `${Math.random() * 10 + 5}px`;
            neuron.style.height = neuron.style.width;
            container.appendChild(neuron);
        }

        for (let i = 0; i < numSynapses; i++) {
            const synapse = document.createElement('div');
            synapse.classList.add('synapse');
            synapse.style.left = `${Math.random() * 100}%`;
            synapse.style.top = `${Math.random() * 100}%`;
            synapse.style.width = `${Math.random() * 200 + 50}px`;
            synapse.style.transform = `rotate(${Math.random() * 360}deg)`;
            container.appendChild(synapse);
        }
    }

    document.addEventListener('DOMContentLoaded', createNeuralNetwork);
</script>
""", unsafe_allow_html=True)

# App title with glow effect
st.markdown('<h1 class="glow">NeuraNexus: AI-Powered ML Assistant</h1>', unsafe_allow_html=True)

# Main content
st.markdown('<h3>Describe your ML challenge, and let NeuraNexus craft an innovative solution.</h3>', unsafe_allow_html=True)
problem_description = st.text_area("", height=150, placeholder="Enter your ML challenge here...")

# Centered Synthesize button
analyze_button = st.button("SYNTHESIZE", key="analyze_button")

# Initialize session state
if 'analysis_result' not in st.session_state:
    st.session_state.analysis_result = ""

if analyze_button:
    if problem_description:
        with st.spinner("NeuraNexus is synthesizing your solution..."):
            llm = ChatGroq(
                temperature=0,
                groq_api_key=GROQ_API_KEY,
                model_name="mixtral-8x7b-32768"
            )

            agent = Agent(
                role="NeuraNexus - Advanced ML Solution Architect",
                goal="Design and explain cutting-edge ML solutions",
                backstory="You are NeuraNexus, a state-of-the-art AI specialized in crafting innovative machine learning solutions.",
                verbose=True,
                allow_delegation=False,
                llm=llm,
            )

            task = Task(
                description=f"Analyze the following ML challenge and provide a detailed solution strategy: {problem_description}",
                expected_output="A comprehensive analysis and innovative solution strategy for the given ML challenge.",
                agent=agent,
            )

            crew = Crew(
                agents=[agent],
                tasks=[task],
                verbose=False
            )

            try:
                result = crew.kickoff()
                st.session_state.analysis_result = str(result)
            except Exception as e:
                st.session_state.analysis_result = f"An error occurred during analysis: {str(e)}"

        st.success("Synthesis complete!")
    else:
        st.warning("Please describe your ML challenge before synthesizing.")

# Display analysis result
if st.session_state.analysis_result:
    st.markdown("### NeuraNexus Synthesis Result")
    st.markdown(f"""
    <div class="result-container">
        {st.session_state.analysis_result}
    </div>
    """, unsafe_allow_html=True)

# By Theaimart text
st.markdown('<p class="by-theaimart">By Theaimart</p>', unsafe_allow_html=True)

# Main function to run the Streamlit app
def main():
    # The main content of the app is already defined above
    # This function can be used to add any additional logic or structure if needed
    pass

if __name__ == "__main__":
    main()