this is my app.py

import os
import tempfile
import streamlit as st
from git import Repo, GitCommandError

from agents import (
    FilterAgent,
    AnalysisAgent,
    ConsolidationAgent,
    ImprovementAgent,
)
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 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"])

    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"))

    with tempfile.TemporaryDirectory() as tmp_dir:
        try:
            with st.spinner("🌀 Cloning repository..."):
                # Use PAT if provided for HTTPS authentication
                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")

            # Loader while FileHandler scans files and Analysis Overview data is prepared
            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
            st.subheader("📄 Architectural Analysis Report")
            if analysis_mode == "Technical Blueprint":
                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)}`")
            else:
                with st.spinner("Generating improvement plan..."):
                    improvements = improvement_agent.generate_improvements(consolidated_summary)
                st.markdown(improvements)

            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()

this is filehander.py
import os
import tiktoken
import streamlit as st

class FileHandler:
    def __init__(self, repo_path: str, agent):
        self.repo_path = repo_path
        self.agent = agent
        self.files = []
        self.excluded_dirs = set()
        self.excluded_files = []
        self.total_scanned = 0
        self.encoder = tiktoken.get_encoding("cl100k_base")
        self._load_files()

    def _load_files(self):
        excluded_dir_names = {
            ".git", ".github", "node_modules", "venv", "dist", "build",
            "__pycache__", "bin", "obj", "packages", "lib", "libs",
            "third_party", "dependencies", ".idea", ".vscode", "coverage"
        }

        for root, dirs, files in os.walk(self.repo_path):
            original_dirs = set(dirs)
            dirs[:] = [d for d in dirs if d not in excluded_dir_names]

            for excluded_dir in (original_dirs - set(dirs)):
                excluded_path = os.path.join(root, excluded_dir)
                self.excluded_dirs.add(os.path.relpath(excluded_path, self.repo_path))

            for f in files:
                self.total_scanned += 1
                full_path = os.path.join(root, f)
                content = self.read_file_content(full_path)
                
                if not content:
                    self.excluded_files.append(os.path.relpath(full_path, self.repo_path))
                    continue
                
                try:
                    should_analyze = self.agent.should_analyze_file(
                        os.path.relpath(full_path, self.repo_path),
                        content[:2000]
                    )
                except Exception as e:
                    st.error(f"Error analyzing {full_path}: {e}")
                    should_analyze = False
                
                if should_analyze:
                    self.files.append(full_path)
                else:
                    self.excluded_files.append(os.path.relpath(full_path, self.repo_path))

    def read_file_content(self, file_path):
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                return f.read()
        except UnicodeDecodeError:
            try:
                with open(file_path, "r", encoding="iso-8859-1") as f:
                    return f.read()
            except Exception:
                return None
        except Exception:
            return None

this is filter agent
import streamlit as st
from datetime import datetime
from pathlib import Path

class FilterAgent:
    def __init__(self, client, deployment, prompt_path):
        self.client = client
        self.deployment = deployment
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

    def log_activity(self, action, file_path=""):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Filter Agent'.ljust(15)} | {action.ljust(25)} | {file_path}"
        self.activity_log.append(log_entry)

    def should_analyze_file(self, file_path, content_sample):
        self.log_activity("Evaluating file", file_path)
        try:
            response = self.client.chat.completions.create(
                model=self.deployment,
                messages=[
                    {"role": "system", "content": self.prompt},
                    {"role": "user", "content": f"File: {file_path}\nContent Sample:\n{content_sample}"}
                ],
                temperature=0,
                max_tokens=10
            )

        except Exception as e:
            st.error(f"FilterAgent API call failed: {e}")
            return False

        decision = response.choices[0].message.content.strip().upper()
        print(f"Filter decision: {decision}", file_path)
        return decision.startswith("YES")

this is analysis agent
import streamlit as st
from datetime import datetime
from pathlib import Path

class AnalysisAgent:
    def __init__(self, client, deployment, prompt_path):
        self.client = client
        self.deployment = deployment
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

    def log_activity(self, action, file_path=""):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Analysis Agent'.ljust(15)} | {action.ljust(25)} | {file_path}"
        self.activity_log.append(log_entry)

    def summarize_file(self, file_path, content):
        self.log_activity("Processing file", file_path)
        try:
            response = self.client.chat.completions.create(
                model=self.deployment,
                messages=[
                    {"role":"system", "content": self.prompt},
                    {"role":"user", "content": f"File: {file_path}\nContent:\n{content}"}
                ],
                temperature=0.1,
            )
        except Exception as e:
            st.error(f"AnalysisAgent API call failed: {e}")
            return ""
        return response.choices[0].message.content

this is consolidate agent

import streamlit as st
from datetime import datetime
from pathlib import Path

class ConsolidationAgent:
    def __init__(self, client, deployment, prompt_path):
        self.client = client
        self.deployment = deployment
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

    def log_activity(self, action):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Consolidation Agent'.ljust(15)} | {action.ljust(25)}"
        self.activity_log.append(log_entry)

    def merge_summaries(self, current_overview, new_summary):
        self.log_activity("Merging summaries")
        try:
            response = self.client.chat.completions.create(
                model=self.deployment,
                messages=[
                    {"role": "system", "content": self.prompt},
                    {"role": "user", "content": f"Current:\n{current_overview}\nNew:\n{new_summary}"}
                ],
                temperature=0.05,
            )
        except Exception as e:
            st.error(f"ConsolidationAgent API call failed: {e}")
            return current_overview
        return response.choices[0].message.content

analysis agent propmt
Analyze how this file contributes to the overall project goals. Provide a detailed explanation covering:

1. Primary purpose in the project context:  
   - What role does this file play within the larger project?  
   - How does it help achieve the project’s main objectives?

2. Key technical implementations:  
   - What are the core functionalities and algorithms implemented here?  
   - Are there any notable patterns, optimizations, or complex logic applied?

3. Relationship to other components:  
   - How does this file interact with or depend on other modules/files?  
   - What is its significance in the data or control flow across the system?

4. Critical design decisions and rationale:  
   - Why was the code structured or implemented this way?  
   - What trade-offs, constraints, or architectural principles influenced these decisions?  
   - How do these affect maintainability, scalability, and performance?

5. Alignment with business and user needs:  
   - How does this file’s functionality deliver business value or support user workflows?  
   - Does it implement essential rules, workflows, or policies?

6. Potential bottlenecks, risks, or improvement areas:  
   - Are there limitations, technical debts, or fragile points to note?  
   - What improvements could enhance future goals?

7. Suggestions for further exploration:  
   - Which related files, modules, or documentation should be reviewed next?  
   - Are there external dependencies, configuration settings, or tests important for context?  
   - What other resources or data flows aid in fully understanding this file’s role?

8. Documentation:  
   - Provide a concise, clear documentation-style summary for this file suitable for project docs or developer onboarding.  
   - Include explanations of the file’s main classes, functions, or interfaces.

9. Code snippets:  
   - Extract and present 2-3 illustrative, important code snippets from this file that demonstrate key functionality or patterns.  
   - Add brief comments or explanations for each snippet to explain why it is important.

Focus on the ‘why’ behind the code, not just ‘what’ it does.

consoldidate agent propmt
Synthesize the individual file analyses into a comprehensive project blueprint. Provide a structured summary covering:

[Project Purpose]  
- What are the core objectives driving the project?  
- What key problem statements or business challenges does the project address?

[Implementation Strategy]  
- Which architectural patterns are employed across the project?  
- What are the primary technology choices and platforms used?  
- Highlight notable design decisions and their rationale affecting system quality (e.g., maintainability, scalability).

[Crucial Components]  
- Identify key files or modules and clearly define their roles within the system.  
- Describe interactions and dependencies between components.  
- Pinpoint where core business logic and critical workflows reside.

[Workflow Overview]  
- Outline the main execution flow and how data moves through the system.  
- Detail important data transformation or processing points.  
- Highlight critical integration points between components, external systems, or services.

[Documentation Summary]  
- Present a consolidated, high-level developer documentation overview from the individual file docs.  
- Include descriptions of key classes, modules, and APIs necessary for understanding the project codebase.

[Representative Code Snippets]  
- Include a selection of significant code snippets across the project that illustrate core logic, design patterns, or complex algorithms.  
- For each snippet, briefly explain its role and importance.

[Risks and Improvement Opportunities]  
- Summarize any potential technical bottlenecks, risks, or areas of technical debt observed.  
- Suggest possible enhancements or refactoring opportunities valuable for future development.

filter agent propmpt

    Determines if a file is critical to the project's logic/operation.
    Returns Only 'YES' or 'NO'  based on below criteria:
    
    === INCLUSION CRITERIA (Include if ANY of these are true) ===
    1. Original Application Logic:
       - Defines core objectives, business rules, or architectural patterns.
       - Contains key workflows (e.g., data pipelines, API endpoints).
       - Critical components (e.g., authentication, payment processing).
       - Functions called across multiple modules.
    
    2. Extended Critical Files:
       - Infrastructure-as-Code (Terraform, Dockerfiles, Helm charts).
       - Database schemas/migrations (SQL, Prisma, ORM configurations).
       - Build/deployment scripts (CI/CD, Bash/Python scripts for workflows).
       - Protocol Buffers/GraphQL schemas defining APIs.
       - Configuration templates with business logic (e.g., Jinja/Kubernetes templates).
    
    3. Human-Authored:
       - Not auto-generated (allow templated files if logic is human-designed).
    
    === EXCLUSION CRITERIA (Exclude if ANY of these are true) ===
    1. Non-Critical Files:
       - Third-party libraries or minified assets.
       - Generated files (lock files, compiled binaries, logs).
       - Generic configs (e.g., .env, .gitignore, IDE settings).
       - Tests/documentation (unless docs define architecture).
       - Static assets (images, fonts, CSS) without embedded logic.
    
    === DECISION LOGIC ===
    Return 'YES' if:
       - File meets AT LEAST 1 INCLUSION criterion AND is human-authored.
       - AND does NOT trigger any EXCLUSION criteria.
    
    Return 'NO' otherwise.
  

Now we want another dropdown which can give us Cloud architecture daigram ehich is maked by first preparing the understanding of whole propject then preparing architecuture flow and then daigram at last i need the well and good daigram with good icons and all coonection

give me full code  what changes we can do