import os
import tempfile
import streamlit as st
import streamlit.components.v1 as components
from git import Repo, GitCommandError

from agents import (
    FilterAgent,
    AnalysisAgent,
    ConsolidationAgent,
    ImprovementAgent,
    DiagramAgent,
)
from file_handling.file_handler import FileHandler
from utils.azure_client import get_azure_client

from dotenv import load_dotenv
load_dotenv()

BASE_PROMPT_DIR = os.path.join(os.path.dirname(__file__), "agents", "prompts")

st.set_page_config(page_title="Project Architecture Analyzer", layout="wide")


def render_mermaid(mermaid_code, height=800):
    # Remove markdown code fences if present
    mermaid_code = mermaid_code.strip()
    if mermaid_code.startswith("```mermaid"):
        lines = mermaid_code.splitlines()
        mermaid_code = "\n".join(lines[1:-1]).strip()
    
    # Debug: show raw code
    st.text_area("Raw Mermaid code for debugging", mermaid_code, height=200)
    
    mermaid_html = f"""
    <div class="mermaid">
    {mermaid_code}
    </div>

    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
      mermaid.initialize({{ startOnLoad: true }});
    </script>
    """

    components.html(mermaid_html, height=height)


def main():
    st.title("🔍 Project Architecture Analyzer")

    repo_url = st.text_input("GitHub Repository URL")

    # Sidebar for credentials & settings
    st.sidebar.header("Configuration")
    pat = st.sidebar.text_input("GitHub Personal Access Token", type="password")
    azure_endpoint = st.sidebar.text_input(
        "Azure OpenAI Endpoint",
        value=os.environ.get("AZURE_OPENAI_ENDPOINT", ""),
    )
    api_key = st.sidebar.text_input(
        "Azure OpenAI API Key",
        type="password",
        value=os.environ.get("AZURE_OPENAI_API_KEY", ""),
    )
    deployment_name = st.sidebar.text_input(
        "Deployment Name",
        value=os.environ.get("AZURE_OPENAI_DEPLOYMENT_NAME", ""),
    )
    analysis_mode = st.sidebar.selectbox("Analysis Mode", ["Technical Blueprint", "Improvement Plan", "Cloud Architecture Diagram"])

    if st.button("Analyze Project"):
        if not all([repo_url, pat, azure_endpoint, api_key, deployment_name]):
            st.error("Please fill in all configuration fields.")
        else:
            run_analysis(repo_url, pat, azure_endpoint, api_key, deployment_name, analysis_mode)


def run_analysis(repo_url, pat, azure_endpoint, api_key, deployment_name, analysis_mode):
    try:
        client = get_azure_client(azure_endpoint, api_key)
    except Exception as e:
        st.error(f"Azure OpenAI client initialization failed: {e}")
        return

    filter_agent = FilterAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "filter_agent_prompt.txt"))
    analysis_agent = AnalysisAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "analysis_agent_prompt.txt"))
    consolidation_agent = ConsolidationAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "consolidation_agent_prompt.txt"))
    improvement_agent = ImprovementAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "improvement_agent_prompt.txt"))
    diagram_agent = DiagramAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "diagram_agent_prompt.txt"))

    with tempfile.TemporaryDirectory() as tmp_dir:
        try:
            with st.spinner("🌀 Cloning repository..."):
                if pat:
                    if not repo_url.startswith("https://"):
                        st.error("PAT can only be used with HTTPS URLs")
                        return
                    auth_repo_url = repo_url.replace("https://", f"https://{pat}@", 1)
                else:
                    auth_repo_url = repo_url

                Repo.clone_from(auth_repo_url, tmp_dir)
            st.success("Repository cloned successfully")

            with st.spinner("🔍 Loading analysis overview..."):
                file_handler = FileHandler(tmp_dir, filter_agent)

                st.subheader("📊 Analysis Overview")
                cols = st.columns(4)
                cols[0].metric("Total Files", file_handler.total_scanned)
                cols[1].metric("Included Files", len(file_handler.files))
                cols[2].metric("Excluded Files", len(file_handler.excluded_files))
                ratio = 0
                if file_handler.total_scanned > 0:
                    ratio = len(file_handler.files) / file_handler.total_scanned * 100
                cols[3].metric("Focus Ratio", f"{ratio:.1f}%")

            consolidated_summary = "## Project Architecture Blueprint\n"
            total_files = len(file_handler.files)

            progress_bar = st.progress(0)
            status_box = st.empty()

            for idx, file_path in enumerate(file_handler.files):
                content = file_handler.read_file_content(file_path)
                rel_path = os.path.relpath(file_path, tmp_dir)

                with st.spinner(f"Analyzing {rel_path}..."):
                    summary = analysis_agent.summarize_file(rel_path, content)
                    consolidated_summary = consolidation_agent.merge_summaries(consolidated_summary, summary)

                progress = (idx + 1) / total_files
                progress_bar.progress(progress)

                status_text = f"""
**Processing:** `{rel_path}`  
**Progress:** {idx + 1}/{total_files} ({progress * 100:.1f}%)  
**Summary Size:** {len(consolidated_summary) // 1024} KB
"""
                status_box.markdown(status_text)

            # Final Report Output
            if analysis_mode == "Technical Blueprint":
                st.subheader("📄 Architectural Analysis Report")
                tab1, tab2 = st.tabs(["Full Report", "Key Components"])
                with tab1:
                    st.markdown(consolidated_summary)
                with tab2:
                    st.markdown("### 🏗️ Architectural Pillars")
                    for file_path in file_handler.files[:10]:
                        st.markdown(f"- `{os.path.basename(file_path)}`")
            elif analysis_mode == "Improvement Plan":
                st.subheader("⚙️ Improvement Plan")
                with st.spinner("Generating improvement plan..."):
                    improvements = improvement_agent.generate_improvements(consolidated_summary)
                st.markdown(improvements)
            else:
                st.subheader("🌥️ Cloud Architecture Diagram")
                with st.spinner("Generating cloud architecture description and diagram..."):
                    architecture_description, mermaid_diagram = diagram_agent.generate_architecture_description(consolidated_summary)

                st.markdown(architecture_description)

                if mermaid_diagram:
                    render_mermaid(mermaid_diagram)
                else:
                    st.warning("No cloud architecture diagram generated.")

            with st.expander("🚫 Excluded Items"):
                st.markdown("#### Directories")
                for d in sorted(file_handler.excluded_dirs):
                    st.markdown(f"- `{d}`")
                st.markdown("#### Files")
                for f in sorted(file_handler.excluded_files):
                    st.markdown(f"- `{f}`")

        except GitCommandError as e:
            st.error(f"Cloning failed: {e}")
        except Exception as e:
            st.error(f"Analysis error: {e}")


if __name__ == "__main__":
    main()

can you make Technical Blueprint and Cloud Architecture Diagram in one  make the changes give me full code display firsth all the Technical Blueprint and then the Cloud Architecture Diagram